更新:如何用JSON文件中的数据动态填充列表? [英] Update: How do I dynamically populate a list with data from a JSON file?

查看:451
本文介绍了更新:如何用JSON文件中的数据动态填充列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用JSON文件中的元素动态填充列表.想法是使用实​​际文件中的JSON文件切换列表中的 test_ID .我该怎么做?

I want to dynamically populate a list with elements from a JSON file. The idea is to switch the test_ID in the list with the actual object from the JSON file. How do I do this?

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>

我确实收到一些错误.线路:

I do receive a couple of errors. The Line:

$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");

出现以下错误:无效的参数数量和未封闭的String文字. 我也不确定如何识别JSON文件中的特定元素.

gives the following error: invalid number of arguments and unclosed String literal. I am also unsure of how to identify to specific elements in the JSON file.

更新 我希望list元素的格式为"Java 2016-08-01"和"JavaScript 2016-08-01".谢谢!

Update I would like if the list element was in this format "Java 2016-08-01" and "JavaScript 2016-08-01". Thank you!

推荐答案

您的javascript中有几个错误.请参阅下面的更正版本:

You have a couple of errors in your javascript. See the corrected version below:

 $(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
        });
    }
   });
 });

这篇关于更新:如何用JSON文件中的数据动态填充列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆