Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.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
使用javascript数组_Javascript_Php - Fatal编程技术网

使用javascript数组

使用javascript数组,javascript,php,Javascript,Php,您好,我有一个php脚本,它成功地从一个外部xml源获取了一个数据数组,该数组名为$file,我知道php数组是使用print\r($file)填充的 我尝试使用以下php传递到javascript会话: //Convert to JSON Array $jsonarray = json_encode($file, JSON_FORCE_OBJECT); $result["json_array"]=$jsonarray; 但是,要么这没有起作用,要么下面的JS代码是错误的: var jsona

您好,我有一个php脚本,它成功地从一个外部xml源获取了一个数据数组,该数组名为$file,我知道php数组是使用print\r($file)填充的

我尝试使用以下php传递到javascript会话:

//Convert to JSON Array
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
但是,要么这没有起作用,要么下面的JS代码是错误的:

var jsonarray = result["json_array"];

alert(JSON.stringify(jsonarray));

有人能告诉我哪里出了问题吗?

你不应该在那里使用JSON.stringify。JSON.parse就是您要查找的内容。因为您想要解析现有的JSON,所以不要创建新的JSON

编辑:你的代码有点奇怪。我想你想要这样的东西

php

js


您必须封装php代码:

<?php
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
?>

var jsonarray = <?= $result["json_array"] ?>;

alert(JSON.parse(jsonarray));

var jsonarray=;
警报(JSON.parse(jsonarray));

是否混合使用PHP和JS变量?此外,您可能希望使用console.log()而不是alert。它将为您提供有关传递给它的对象中包含的内容的更多信息,特别是当您处理数组时。
alert(JSON.parse(data)); // Where data is the contents you've fetched from the server
<?php
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
?>

var jsonarray = <?= $result["json_array"] ?>;

alert(JSON.parse(jsonarray));