2017-04-08 103 views
0

我在JSON中有一點經驗我在我的Android應用程序中做了它,現在在我的網頁中再次使用JSON作爲AJAX響應,我研究了ajax並找到了一個教程來獲取數據庫中的數據使用JSON,所以我試過,但我不知道如何解析對象。如何解析JQuery中的Json對象

我的jquery代碼。

$.ajax({ 
    type: 'GET', 
    dataType: 'json', 
    url: 'functions/json.php', 
    success: function(response){ 
    var json = $.parseJSON(response); 
    alert(json.firstname) //where my response is $response['firstname'] 
}, 
error: function(data){ 
    var json = $.parseJSON(data); 
    alert(json.error); 
} 
}); 

使用我附和jsonArray爲json_encode在PHP和繼承人使用谷歌瀏覽控制檯的JSON輸出

{"id":"2","firstname":"john","lastname":"Doe"} 

我得到這個錯誤

Uncaught SyntaxError: Unexpected token o in JSON at position 1 
at JSON.parse (<anonymous>) 

當函數響應輸出警報(響應) 輸出爲

[object Object] 

回答

3

不要解析它。你已經告訴了jQuery:

dataType: "json" 

所以response解析對象,而不是JSON。只需直接使用它:

$.ajax({ 
    type: 'GET', 
    dataType: 'json', 
    url: 'functions/json.php', 
    success: function(response){ 
     alert(response.firstname); 
    }, 
    error: function(data) { 
     // `data` will not be JSON 
    } 
}); 

還要注意的error回調的第一個參數不會JSON或錯誤回調JSON解析的結果。詳情請參閱the documentation

+0

非常感謝你在ajax最新的答案,但我會等到12分鐘:) :) –

+0

{「成功」:真,「消息」:[{「id」:「2」,「firstname」:「john」 ,「lastname」:「doe」},[{「id」:「3」,「firstname」:「jane」,「lastname」:「doe」}]} 使用多個數組我將如何迴應? –

+0

@RaizeTech:我只看到一個數組。要循環訪問該數組(即'response.message'),請使用[此問題的答案]中涵蓋的任何技術(http://stackoverflow.com/questions/9329446/for-each-over-an-array- in-javascript),比如'response.message.forEach(function(entry){alert(entry.firstname);});' –