简体   繁体   English

脚本类型=“ text / javascript”变量无法捕获PHP回显的JSON

[英]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. 我正在开发一个PHP Web应用程序,该应用程序从MYSQL数据库检索数据负载,然后使用PHP的json_encode将关联数组转换为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 . 以前似乎可以正常工作,但是现在在chrome中按F12键并检查控制台时,JavaScript抛出错误,因为它无法识别<?php的开头<。

I've found that if I remove the type="text/javascript" from the script tag, it reads it fine. 我发现,如果我从脚本标记中删除type =“ text / javascript”,它会正常运行。

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. 似乎在script标签中添加类型会阻止PHP在发送给客户端设备之前执行。

Why is this? 为什么是这样?

It appears that the tag can actually be used to run PHP code, if you use: 如果您使用以下标签,则该标签实际上可以用于运行PHP代码:

<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. 我假设在script标记中设置类型会使其仅评估标记中的一种​​语言-保留该类型而无需保留类型则使其保留多语言脚本标记。

Source: http://php.about.com/od/advancedphp/qt/mixed_scripting.htm 资料来源: 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. 将评估两种语言(显然是PHP服务器端),但是在script标记中设置类型或语言将阻止评估标记中的其他语言/类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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