使用xmlhttp.responseText中的JSON解析数组

时间:2013-08-03 11:51:42

标签: php javascript arrays json

我试图使用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}

在firebug上我遇到语法错误:

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

array1 = JSON.parse(xmlhttp.responseText);
我做错了什么?我需要在JS中使用这个数组,我该如何正确编码呢?

提前致谢

4 个答案:

答案 0 :(得分: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}

答案 1 :(得分:0)

检查内容类型:

  header('Content-type: application/json');

答案 2 :(得分:0)

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

答案 3 :(得分: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