簡體   English   中英

使用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。

我希望你的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM