json不能't使用标签更改数据

json couldn't change the dataWithLabels

本文关键字:标签 数据 不能 json      更新时间:2023-09-26

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

由于我不知道,如果你请求的JSON是正确的,我只是假设它是正确的。不过,如果你想看看在Ajax请求之后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请求之前提醒状态。

希望能有所帮助!

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

});