Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从Ajax请求解码JSON数组_Php_Javascript_Json - Fatal编程技术网

Php 从Ajax请求解码JSON数组

Php 从Ajax请求解码JSON数组,php,javascript,json,Php,Javascript,Json,我终于成功地使用Ajax从一个页面发送到另一个页面!我试图做的是将一个数组从一个PHP文件传递到一个Javascript文件,Javascript文件在this.responseText中接收这个数组: <html> <head> <script type="text/javascript"> var jsonArray = ["chickens","horses","cows","werewolves","zombies","vam

我终于成功地使用Ajax从一个页面发送到另一个页面!我试图做的是将一个数组从一个PHP文件传递到一个Javascript文件,Javascript文件在
this.responseText
中接收这个数组:

<html>
<head>

    <script type="text/javascript">
        var jsonArray = ["chickens","horses","cows","werewolves","zombies","vampires","phantoms","U.S. Congressmen","performance artists","pieces of fencepost","barnhouses","robots","cyborgs"]

    </script>
</head>
</html>
第二次编辑包含数组的文件(PHP)如下所示:

<html>
<head>
<?php

$victims = array(

    // Animals
    "chickens",
    "horses",
    "cows",

    // Supernatural
    "werewolves",
    "zombies",
    "vampires",
    "phantoms",

    // Human
    "U.S. Congressmen",
    "performance artists",

    // Inanimate, non-mechanical
    "pieces of fencepost",
    "barnhouses",

    // Mechanical
    "robots",
    "cyborgs"

);

?>

    <script type="text/javascript">
        var jsonArray = <?php echo json_encode($victims); ?>


    </script>
</head>
</html>

var jsonArray=

您可以在上使用库,也可以使用eval(“+this.responseText+”)


通常,您希望使用库来解析JSON字符串而不是eval,因为eval通常是不安全的。

如果您的php页面返回您报告的所有文本(以及等等),那么您的输出不是JSON对象,而是html页面。您的响应应该只包含序列化的JSON对象(以及正确的http响应头)

“清理”输出后,可以使用JSON2库解析对象:


这看起来不像是来自服务器的正确JSON响应,因为它包含HTML代码,然后是一块javascript。响应应该只包含包含数据的javascript代码,如

var data = ["chickens","horses","cows","werewolves","zombies"]";
然后可以对字符串求值(),它就会工作

如上所述,eval()可能不安全,因此,如果使用jQuery,可以使用安全的函数

要正确返回JSON,根本不在页面中输出HTML,只需执行以下操作

<?php

    $victims = ...; // fill array

    echo json_encode($victims);
?>


您是否返回http 200状态码?使用firebug来确定是脚本什么都不返回还是调用完全失败。好的,所以我把数组放在了一个.json文件中,但现在eval提出了
未定义的
。我不确定“我把数组放在了一个json文件中”是什么意思。php文件应该对post数据进行您需要的任何处理,然后只回显JSON数据。您还应该将响应类型设置为“text/json”。使用firebug mozilla扩展来检查您发送和接收的内容,ajax调用应该只返回转义的javascript代码
var data = ["chickens","horses","cows","werewolves","zombies"]";
<?php

    $victims = ...; // fill array

    echo json_encode($victims);
?>