如何使用 JQUERY 从 JSON 数组对象获取数据?



如何使用jquery从JSON数组对象中获取所有数据?
我以前试过,但我的代码只能从 JSON 对象获取数据。

这是我的json文件学生.json

{"status":true,
"offset":0,
"limit":25,
"total":2,
"data":[
{ "id":231,
"title":"mytitle1",
"content":"myconten1",
"created_at":"2017-07-10 03:56:32",
"updated_at":"2017-07-10 03:56:32"
},{ "id":230,
"title":"mytitle2",
"content":"mycontent2",
"created_at":"2017-07-10 03:56:06",
"updated_at":"2017-07-10 03:56:06"
}]}

我的js脚本:

<script>
$(document).ready(function(){
$(function (){
var $orders = $('#orders');
$.ajax({
type: 'GET',
url: 'json/student.json',
success: function(data) {
console.log('success', data);
$.each(data, function(i, dataentry){
$orders.append('<li>dataid: '+dataentry.id+'</li>');
});
}
});
});
});
</script>

所以首先,你不需要写这个:

$(document).ready(function(){  
$(function (){

因为$(function()(不带空格(是$(document).ready(function()的缩写。

关于你的问题 - 我相信data是整个 JSON,所以你需要提取data.data,所以我会写这个:

$(function (){
var $orders = $('#orders');
$.ajax({
type: 'GET',
url: 'json/student.json',
success: function(response) {      // <= this is the change
var data = response.data;      // <= going inside the data itself
$.each(data, function(i, data){
$orders.append('<li>dataid: '+data.id+'</li>');
});
}
});
});

success函数中,收到的data是 ajax 调用的实际数据响应。

你应该在console.log语句中看到它,其中包含所有属性,如offsetlimittotal等。

无论如何,您正在尝试遍历整个对象,而不是响应中的data属性,这实际上是您可能想要循环的数组。您不会收到任何错误$.each因为它可以遍历对象文字以及数组。

下面是它的外观(我调整了变量名称以使其更清晰(:

success: function(response) {
$.each(response.data, function(i, dataEntry){     // or response['data']
$orders.append('<li>dataid: '+dataEntry.id+'</li>');
});
}

希望对您有所帮助。

如果您的 ajax 调用成功,则:

  • 函数(数据(:此数据是从服务器返回的基本对象,在您的情况下,它不是数据属性。

  • 现在,JSON 中的数据是一个数组。

因此,与其在根对象上使用 forEACH,不如在data.data上使用它。 希望会有所帮助。

在这里,您将提供一个示例解决方案 https://jsfiddle.net/xydqLLdb/

var response = {"status":true,
"offset":0,
"limit":25,
"total":2,
"data":[
{ "id":231,
"title":"mytitle1",
"content":"myconten1",
"created_at":"2017-07-10 03:56:32",
"updated_at":"2017-07-10 03:56:32"
},{ "id":230,
"title":"mytitle2",
"content":"mycontent2",
"created_at":"2017-07-10 03:56:06",
"updated_at":"2017-07-10 03:56:06"
}]};

$.each(response.data, function(i, data){
$('ul').append('<li>dataid: ' + data.id + '</li>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
</ul>

基于你的方案

$(document).ready(function(){  
$(function (){
var $orders = $('#orders');
$.ajax({
type: 'GET',
url: 'json/student.json',
success: function(response) {
$.each(response.data, function(i, data){
$orders.append('<li>dataid: ' + data.id + '</li>');
});
}
});
});
});

您需要使用repsonse 数据遍历datakey

希望这对您有所帮助。

最新更新