简体   繁体   中英

Script type=“text/javascript” variable not catching PHP echoed JSON

I'm working on a PHP web app that retrieves loads of data from a MYSQL database, then uses PHPs json_encode to convert the associative arrays into JSON.

<script type="text/javascript">
    var json = <?php
    // get loads of data from MYSQL database, store in $array
    echo(json_encode($array));
    ?>;
</script>

This appeared to work fine before, but now when pressing F12 in chrome and checking the console, JavaScript throws an error as it doesn't recognize the opening < in the <?php .

I've found that if I remove the type="text/javascript" from the script tag, it reads it fine.

EDIT:

If I use the following, it works:

<script>
    var json = <?php
    // get loads of data from MYSQL database, store in $array
    echo(json_encode($array));
    ?>;
</script>

It seems that adding a type to the script tag prevents PHP from executing prior to it being sent to the client side device.

Why is this?

It appears that the tag can actually be used to run PHP code, if you use:

<script language="php"> echo("hello"); </script>

I assume that setting a type in the script tag makes it only evaluate a single language within the tags - leaving it without a type allows it to stay a multi-language script tag.

Source: http://php.about.com/od/advancedphp/qt/mixed_scripting.htm

Therefore, using something like

<script>
var json = <?php
echo($var);
?>;
</script>

will evaluate both languages (obviously PHP server side), but setting a type or language in the script tag will prevent other languages / types within the tags from being evaluated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM