简体   繁体   English

如何让Json成为Ajax $ .getJSON()的关键和价值?

[英]How to get Json as key and value in the Ajax $.getJSON()?

I have this ajax code for getting json from Jobs.json file. 我有这个ajax代码从Jobs.json文件获取json。

 $(document).ready(function(){
        $('#btn2').click( callJobs );
        });

function callJobs()
{


     alert("getting results...");
    $.getJSON('Jobs.json', function(JSON){
        $('#result').empty();

        $.each(JSON.jobs, function(i, JOB){
            $('#result')
            .append(JOB.Job +'<br />')
            .append(JOB.Priority+'<br />')
            .append(JOB.DueDate+'<br />')
            .append(JOB.Iscompleted+'<hr />');
      });
    });
}

Jobs.json code is below. Jobs.json代码如下。

{
"jobs":[
  {
     "Job":"Job1",
     "Priority":"Low",
     "DueDate":"11.03.2013",
     "Iscompleted":"No"
  },
  {
     "Job":"Job2",
     "Priority":"High",
     "DueDate":"11.03.2013",
     "Iscompleted" : "No"
  },
  {
     "Job":"Job3",
     "Priority":"Medium",
     "DueDate":"11.03.2013",
     "Iscompleted":"No"
  }
  ]
  }

Now I want to rewrite $.each function dynamically.That is, it will write the json string as key and value instead of .append() . 现在我想动态地重写$ .each函数。也就是说,它会将json字符串写为键和值而不是.append()。

This would walk over the properties of each job dynamically: 这会动态地遍历每个作业的属性:

$.getJSON('Jobs.json', function(JSON){
    var $container = $('#result').empty();

    $.each(JSON.jobs, function(i, JOB) {
        $.each(JOB, function(key, value) {
            $container.append(key + ': ' + value + '<br />');
        });
        $container.append('<hr />');
    }
});

Demo 演示

Here's my approach. 这是我的方法。 I've added comments to explain the process. 我添加了评论来解释这个过程。

$.each(JSON.jobs, function(i, JOB) {
    // an empty array for the output values
    var values = [];
    // iterator over each property in the current JOB object
    for (var prop in JOB) { 
        // add an item to the array in format "key: value"
        values.push(prop + ': ' + JOB[prop]); 
    }
    // join the array values using '<br />' as separator; 
    // append to #result and add an '<hr />' after
    $('#result').append(values.join('<br />')).append('<hr />');
});

My goals for this solution were to keep it readable (at the cost of an added array), select the #result element only once, and not have to deal with knowing whether to add that last <br /> during each loop. 我对这个解决方案的目标是,以保持它的可读性(在加入阵列的成本),选择#result只有一次元素,而不必应付知道是否增加,去年<br />每个循环中。 The other solutions append an extra <br /> after the last property and before the <hr /> whereas this and your original solution do not. 其他解决方案在最后一个属性之后和<hr />之前添加了额外的<br /> ,而这个和原始解决方案没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM