[英]Update: How do I dynamically populate a list with data from a JSON file?
我想用JSON文件中的元素動態填充列表。 這個想法是用JSON文件中的實際對象來切換列表中的test_ID 。 我該怎么做呢?
JSON文件
[
{
"id": "a",
"test": "Java",
"testDate": "2016-08-01"
},
{
"id": "b",
"test":"JavaScript",
"testDate": "2016-08-01"
}
]
jQuery的
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
});
$("#test_ID").empty(); //emtpy the UL before starting
$.each(arr_json, function(i, v, d) {
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
});
}
});
});
HTML
<li id="test_ID"></li>
我確實收到一些錯誤。 線:
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
給出以下錯誤:參數數量無效和未封閉的String文字。 我也不確定如何識別JSON文件中的特定元素。
更新我想如果列表元素的格式為“ Java 2016-08-01”和“ JavaScript 2016-08-01”。 謝謝!
您的JavaScript有幾個錯誤。 請參閱下面的更正版本:
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
$("#test_ID").empty(); //emtpy the UL before starting
// **************** correction made to the line below ***********************
$.each(result, function(i, v, d) {
// **************** correction made to the line below ***********************
$("#test_ID").append('<li id="' + v.id + '">' + v.test + ' ' + v.testDate + '</li>'); // correction made here
});
}
});
});
我做了個小提琴。 我不太了解v.test在HTML標記內未標記的情況,所以我沒有包括它。 我使用最少的JQuery來避免復雜性。
https://jsfiddle.net/ndx5da97/
for (record in data) {
$("#test_ID").append('<li id="' + data[record].id + '">' + data[record].testDate + '</li>');
}
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.