如何使用 jquery 从 JSON 数组对象中获取所有数据?
我之前尝试过,但我的代码只能从 JSON 对象中获取数据。
这是我的 json 文件student.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()
(w/oa space) 是$(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>');
});
}
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句