2017-04-08 99 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);});' –