我正在尝试使用 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 中使用这个数组,如何正确编码?
提前致谢