0

我正在尝试使用 ajax 将 php 数组转换为 js,并在 PHP 中通过 JSON 编码并在 JS 中解码,但无法获得所需的结果。

我在回显编码字符串之前使用 var_dump,这是输出:

$boardArrayEncoded = json_encode($boardArray);
var_dump($boardArrayEncoded);
echo $boardArrayEncoded;

JSON_encode 之后的这个字符串是:

string '{"1x1":0,"1x2":0,"1x3":0,"1x4":0,"1x5":0,"1x6":0,"2x1":0,"2x2":0,"2x3":0,"2x4":0,"2x5":0,"2x6":0,"3x1":0,"3x2":0,"3x3":0,"3x4":0,"3x5":0,"3x6":0,"4x1":0,"4x2":0,"4x3":0,"4x4":0,"4x5":0,"4x6":0,"5x1":0,"5x2":0,"5x3":0,"5x4":0,"5x5":0,"5x6":0,"6x1":0,"6x2":0,"6x3":0,"6x4":0,"6x5":0,"6x6":0}'

在javascript中我尝试解析它:

if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
   document.getElementById("logDiv1").innerHTML = xmlhttp.responseText;
   array = JSON.parse(xmlhttp.responseText);
}

这是 xmlhttp.responseText: {"1x1":0,"1x2":0,"1x3":0,"1x4":0,"1x5":0,"1x6":0,"2x1":0,"2x2":0,"2x3":0,"2x4":0,"2x5":0,"2x6":0,"3x1":0,"3x2":0,"3x3":0,"3x4":0,"3x5":0,"3x6":0,"4x1":0,"4x2":0,"4x3":0,"4x4":0,"4x5":0,"4x6":0,"5x1":0,"5x2":0,"5x3":0,"5x4":0,"5x5":0,"5x6":0,"6x1":0,"6x2":0,"6x3":0,"6x4":0,"6x5":0,"6x6":0}

在萤火虫我得到语法错误:

SyntaxError: JSON.parse: unexpected character
[Break On This Error]   

array1 = JSON.parse(xmlhttp.responseText);

我做错了什么?我需要在 JS 中使用这个数组,如何正确编码?

提前致谢

4

4 回答 4

2

删除 var_dump。它是打印输出,这可能导致您所说的 responseText 不是完整的 responseText。

我希望您的 responseText 是:

string '{"1x1":0,"1x2":0,"1x3":0,"1x4":0,"1x5":0,"1x6":0,"2x1":0,"2x2":0,"2x3":0,"2x4":0,"2x5":0,"2x6":0,"3x1":0,"3x2":0,"3x3":0,"3x4":0,"3x5":0,"3x6":0,"4x1":0,"4x2":0,"4x3":0,"4x4":0,"4x5":0,"4x6":0,"5x1":0,"5x2":0,"5x3":0,"5x4":0,"5x5":0,"5x6":0,"6x1":0,"6x2":0,"6x3":0,"6x4":0,"6x5":0,"6x6":0}'
{"1x1":0,"1x2":0,"1x3":0,"1x4":0,"1x5":0,"1x6":0,"2x1":0,"2x2":0,"2x3":0,"2x4":0,"2x5":0,"2x6":0,"3x1":0,"3x2":0,"3x3":0,"3x4":0,"3x5":0,"3x6":0,"4x1":0,"4x2":0,"4x3":0,"4x4":0,"4x5":0,"4x6":0,"5x1":0,"5x2":0,"5x3":0,"5x4":0,"5x5":0,"5x6":0,"6x1":0,"6x2":0,"6x3":0,"6x4":0,"6x5":0,"6x6":0}
于 2013-08-03T11:58:45.287 回答
0

http://jsfiddle.net/ELc8L/

var responseText='{"1x1":0,"1x2":0,"1x3":0,"1x4":0,"1x5":0,"1x6":0,"2x1":0,"2x2":0,"2x3":0,"2x4":0,"2x5":0,"2x6":0,"3x1":0,"3x2":0,"3x3":0,"3x4":0,"3x5":0,"3x6":0,"4x1":0,"4x2":0,"4x3":0,"4x4":0,"4x5":0,"4x6":0,"5x1":0,"5x2":0,"5x3":0,"5x4":0,"5x5":0,"5x6":0,"6x1":0,"6x2":0,"6x3":0,"6x4":0,"6x5":0,"6x6":0}'; // Your JSON string.
parsedJSON=eval('('+responseText+')'); // Parsed JSON. Object.
alert(parsedJSON["1x1"]); // Access object element's like this, because you can't write parsedJSON.1x1;
for(element in parsedJSON){
    document.body.innerHTML+=element+" => "+parsedJSON[element]+"<br />";
} // Just a vardump to show everything's perfect
于 2013-08-03T12:28:01.317 回答
0

检查内容类型:

  header('Content-type: application/json');
于 2013-08-03T12:01:48.327 回答
0

确保您只有echo $boardArrayEncoded;并且没有其他输出。还要确保没有前导空格或换行符,因为这也会破坏有效的 JSON 数据。在执行回显之前,请包含header('Content-type: application/json');以将输出准备为 JSON。

于 2013-08-03T12:02:00.333 回答