2012-01-03 54 views
1

我正在從PHP服務器回傳JSON到瀏覽器。我很熟悉XML,但是對於JSON來說是新的。有人可以告訴我如何從xmlhttpRequest中正確提取JSON,然後將它傳遞給數據或警報。在JS中通過xmlhttp請求傳遞JSON

我的JSON(從PHP服務器)

 {"data": { 
     "message": "Open the Pod bay doors, Hal", 
     "type": "request",   
     "replies" => array(
       "id": "12321" 
       "message": "I'm sorry Dave, I'm afraid I can't do that!" 
     ) 
     } 
     } 

我在JS請求返回的JSON但是我沒有抓住它或提取內幕信息的途徑......我的AJAX功能...

function ajax(site){ 
    xmlhttp.open("GET","site",true); 
    xmlhttp.onreadystatechange=function() { 
    if (xmlhttp.readyState==4) { 
     if (xmlhttp.status!=404) { 
     var resp =new Function("return "+xmlhttp.responseText)(); 

    } 
    } 
xmlhttp.send(null); 
} 

然後我調用在在window.onload

window.onload = runJSON() 

function runJSON(){ 
    var site = "http://localhost/sites/sandbox/json.php" 
    ajax(site); 
    ... this is what i am unsure about... how do I access the data in the object 
} 
alert(data); 
} 

回答

1
"replies" => array(
      "id": "12321" 
      "message": "I'm sorry Dave, I'm afraid I can't do that!" 
    ) 
功能

必須

"replies": { 
    "id": "12321", 
    "message": "I'm sorry Dave, I'm afraid I can't do that!" 
} 
在JavaScript

,您可以JSON轉換爲JS對象通過運行​​,你應該從一個回調從onreadystatechange處理程序中讓你str

if (xmlhttp.status!=404) { 
    var resp =new Function("return "+xmlhttp.responseText)(); 
    ajaxDone(resp); 
} 
function ajaxDone(str) { 
    try { 
    var data = JSON.parse(str); 
    console.log(data); 
    } catch (x) { 
    // TODO: see what happened 
    } 
} 

注意:舊版瀏覽器中不存在JSON.parse。如果你也希望支持他們,你需要一個能夠讓他們興奮的庫,比如jQuery(這會偶然地帶走AJAX部門的很多痛苦)。

1

首先,您應該解析該JSON數據並將其從ajax函數返回。

var resp =new Function("return "+xmlhttp.responseText)(); 

變化與此一致,

return JSON.parse(xmlhttp.responseText); 

然後在runJSON功能,採取JSON對象到變量中。

var jd = ajax(site); 

然後你可以訪問json中的所有數據。

例如。 alert(jd.data.message);可讓您在屏幕上顯示「打開Pod艙門,Hal」信息。