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


parse array with JSON from xmlhttp.responseText

我试图使用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中使用这个数组,如何正确编码?

提前感谢

移除var_dump。它是打印输出,这可能导致您所说的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}

检查内容类型:

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

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

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