【问题标题】:json couldn't change the dataWithLabelsjson 无法更改 dataWithLabels
【发布时间】:2015-12-07 21:30:14
【问题描述】:

请您帮忙查看代码。我想将标题名称从“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 对象的标题

【问题讨论】:

标签: javascript jquery json ajax get


【解决方案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.
  });

现在,在您插入 statistic.temp_c 后,dataWithLabels 的状态会收到警报。您的代码始终在 Ajax 请求之前提醒状态。

希望有帮助!

【讨论】:

  • 你做了什么改变,为什么?
  • 我把你的 alert 放在了 for 循环中。因为那是您为数组分配新值的地方。 Ajax 的要点是在请求成功完成后调用成功函数。原始代码中的警报将在成功函数之前执行。 - 异步-
  • 这不是我的代码,但感谢您的澄清。所以基本上你同意这是上面 cmets 中链接问题的重复?
  • 啊,对不起。是的,它是重复的。
【解决方案2】:

这是因为 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
      }

  }

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2019-09-13
    • 2019-12-12
    • 2012-04-23
    • 2012-12-29
    相关资源
    最近更新 更多