json无法更改dataWithLabels

时间:2015-12-07 21:30:14

标签: javascript jquery json ajax get

请帮忙看看代码。我想将标题名称从'Jason'更改为JSON文件中写入的温度。

var dataWithLabels = [
{
   "title":"Jason",  
}];

 $.ajax({
    url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
    type: "GET",
    dataType: "json", 
    success: function(data) {
    for(var i=0;i<1/*dataWithLabels.length*/;i++){
       var statistic = data.current_observation;
       dataWithLabels[i]['title']= statistic.temp_c;}} 
       //wanted to change Jason to the temperature written at the JSON file.Please help.
    });

 alert(dataWithLabels[0]['title']); 

http://codepen.io/wtang2/pen/bEGQKP

这不是重复,我试图将结果从JSON文件替换为dataWithLabels对象的标题

2 个答案:

答案 0 :(得分:1)

由于我不知道,如果您要求的JSON是正确的,我只是假设它是。不过,如果你想看看,在你的Ajax-Request之后dataWithLabels中发生了什么,你需要稍微改写一下这个函数:

   var dataWithLabels = [{
    "title": "Jason",
  }];

  $.ajax({
    url:     "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
    type: "GET",
    dataType: "json",
    success: function(data) {
        for (var i = 0; i < 1 /*dataWithLabels.length*/ ; i++) {
          var statistic = data.current_observation;
          dataWithLabels[i]['title'] = statistic.temp_c;
          alert(dataWithLabels[i]['title']);
        }

      }
      //wanted to change Jason to the temperature written at the JSON  file.Please help.
  });

现在,在您插入dataWithLabels后,statistic.temp_c的状态会被警告。您的代码始终在Ajax请求之前警告状态。

希望有所帮助!

答案 1 :(得分:1)

这是因为AJAX请求异步工作,因此您需要在完成AJAX请求后才能提醒结果

var dataWithLabels = [{
   "title": "Jason",
}];

$.ajax({
  url: "http://api.wunderground.com/api/2b38dcff93aa3dff/conditions/q/CA/Santa_Clara.json",
  type: "GET",
  dataType: "json",
  success: function(data) {
      for (var i = 0; i < 1 /*dataWithLabels.length*/ ; i++) {
         var statistic = data.current_observation;
         dataWithLabels[i]['title'] = statistic.temp_c;
         alert(dataWithLabels[i]['title']); // Alert only after data is received
      }

  }

});