简体   繁体   English

关于jQuery中的getJSON函数

[英]About getJSON function in jQuery

{
   "Adam":{
      "Math":"93",
      "Science":"96",
      "Email":"adam@example.com",
      "City":"NY"
   },
   "Tom":{
      "Math":"65",
      "Science":"56",
      "Email":"tom@example.com",
      "City":"LA"
   },
   "Joe":{
      "Math":"74",
      "Science":"83",
      "Email":"joe@example.com",
      "City":"Washington"
   }
}

Above is the JSON content present at the http: //ActualUrl/path.json 上面是http://ActualUrl/path.json上的JSON内容

I am accessing the JSON file and filling the two arrays with name and marks in science with the code below. 我正在访问JSON文件,并使用下面的代码用科学的名称和标记填充两个数组。

     var names=[];
     var marks=[];
    $.getJSON("http://path.json",function(data){               
                $.each(data, function(key, val) {   
                     names.push(key);
                    // I placed alert the check the value key.
            marks.push(parseInt(val.Science));                  
                    });
                });
    alert(names.toString()); // names is found blank
    alert(marks.toString()); 

When I check the array at the end. 当我最后检查数组时。 Array is found blank. 数组为空。 Why this wrong behaviour with getJSON ? 为什么getJSON出现这种错误行为? I placed alert in the each and check the value. 我在每个警报中放置了一个,然后检查该值。 It returns correct value. 它返回正确的值。

$.getJSON fires off asynchronously, meaning that in most cases it will not have completed by the time you read out your variables. $.getJSON异步触发,这意味着在大多数情况下,到您读出变量时,它尚未完成。 You will need to restructure your solution such that you do the thing you want to do within it's success callback: 您将需要重组解决方案,以便在成功回调中执行您想做的事情:

$.getJSON("http://path.json", function(data) {
    $.each(data, function(key, val) {
        names.push(key);
        marks.push(parseInt(val.Science));
    });

    // do your thing here.
});

Primary problem 主要问题

You are filling your array in the async callback, but alert them right away. 您正在异步回调中填充数组,但立即提醒它们。 So, this is what happens: 因此,将发生以下情况:

  1. You execute ajax call. 您执行ajax调用。 Request is sent to the server. 请求被发送到服务器。

  2. You alert values of arrays. 您警报数组的值。 They are blank, since the server didn't reply yet. 它们为空,因为服务器尚未回复。

  3. Server replies, your callback is fired and arrays are filled. 服务器回复,触发您的回调并填充数组。 Too late. 太晚了。

Solution: 解:

Put alert logic to the callback. 将警报逻辑放入回调中。

Other notes 其他注意事项

jQuery.each is for iterating collections. jQuery.each用于迭代集合。 You, on the other hand, have an object (or dictionary). 另一方面,您有一个对象(或字典)。

Try this code: 试试这个代码:

for(key in data) {
  names.push(key);
  var val = data[key];
  marks.push(parseInt(val.Science));                  
}

for ... in ... construct iterates object properties, which is what you want. for ... in ...构造会迭代对象属性,这就是您想要的。

$.each Description: Iterate over a jQuery object, executing a function for each matched element. $ .each描述:遍历jQuery对象,为每个匹配的元素执行一个函数。 (from: http://api.jquery.com/each/ ) (来自: http : //api.jquery.com/each/

The returned JSON is not a jQuery object, just a plain JavaScript object. 返回的JSON不是jQuery对象,而只是普通的JavaScript对象。 Use foreach(key in data) instead. 改用foreach(输入数据)。

Oh and move the alert() inside the callback function :) 哦,将alert()移到回调函数中:)

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

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