Javascript 如何在Jquery中解析Json对象
我在JSON方面有点经验,我在Android应用程序上使用JSON,现在在我的网页上再次使用JSON作为AJAX响应,我研究了AJAX,找到了一个教程,可以使用JSON在数据库中获取数据,所以我试过,但我不知道如何解析对象 我的Jquery代码Javascript 如何在Jquery中解析Json对象,javascript,php,jquery,json,ajax,Javascript,Php,Jquery,Json,Ajax,我在JSON方面有点经验,我在Android应用程序上使用JSON,现在在我的网页上再次使用JSON作为AJAX响应,我研究了AJAX,找到了一个教程,可以使用JSON在数据库中获取数据,所以我试过,但我不知道如何解析对象 我的Jquery代码 $.ajax({ type: 'GET', dataType: 'json', url: 'functions/json.php', success: function(response){ var json = $
$.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);
}
});
使用php,我将jsonArray作为json_编码进行回显,这里是json输出
{"id":"2","firstname":"john","lastname":"Doe"}
使用谷歌chrome控制台我得到了这个错误
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
不要解析它。您已经告诉jQuery:
dataType: "json"
因此,响应是已解析的对象,而不是JSON。直接使用即可:
$.ajax({
type: 'GET',
dataType: 'json',
url: 'functions/json.php',
success: function(response){
alert(response.firstname);
},
error: function(data) {
// `data` will not be JSON
}
});
还要注意,错误回调的第一个参数不是JSON,也不是错误回调中解析JSON的结果
有关详细信息,请参阅。不要解析它。您已经告诉jQuery:
dataType: "json"
因此,响应是已解析的对象,而不是JSON。直接使用即可:
$.ajax({
type: 'GET',
dataType: 'json',
url: 'functions/json.php',
success: function(response){
alert(response.firstname);
},
error: function(data) {
// `data` will not be JSON
}
});
还要注意,错误回调的第一个参数不是JSON,也不是错误回调中解析JSON的结果
有关详细信息,请参阅。感谢您在ajax中提供了这么多新的最佳答案,但我会等到12分钟:{success:true,message:[{id:2,firstname:john,lastname:doe},[{id:3,firstname:jane,lastname:doe}}使用多个数组我将如何回应这个问题?@RaizeTech:我在其中只看到一个数组。要循环遍历该数组,即response.message,请使用中介绍的任何技术,例如response.message.forEachfunctionentry{alertentry.firstname;};感谢您在ajax中提供了这么多新的最佳答案,但我将等待12分钟:{success:true,message:[{id:2,firstname:john,lastname:doe},[{id:3,firstname:jane,lastname:doe}]}使用多个数组我该如何回显它?@RaizeTech:我在其中只看到一个数组。要循环通过response.message数组,请使用response.message.forEachfunctionentry{alertentry.firstname;};