ajax - jquery布尔平等表演搞笑

时间:2017-05-03 11:50:08

标签: jquery json ajax

我有一个从openweathermap.org请求天气数据的api

var requestWeatherData = function(ipData){
      $.ajax({
        url: "http://api.openweathermap.org/data/2.5/weather",
        dataType: "json",        
        data: {
          q: ipData.city + ',' + ipData.countryCode,
          appid: "cant say"
        },
        success: function(wthrDetails) {                       
          addWeatherIcon(wthrDetails)             
        },
      });

来自api的示例回复是:

{"coord":
{"lon":145.77,"lat":-16.92},
"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],
"base":"cmc stations",
"main":{"temp":293.25,"pressure":1019,"humidity":83,"temp_min":289.82,"temp_max":295.37},
"wind":{"speed":5.1,"deg":150},
"clouds":{"all":75},
"rain":{"3h":3},
"dt":1435658272,
"sys":{"type":1,"id":8166,"message":0.0166,"country":"AU","sunrise":1435610796,"sunset":1435650870},
"id":2172797,
"name":"Cairns",
"cod":200}

但是当我尝试通过上面的回复获取天气状态时:

var addWeatherIcon = function(weatherDetails) {
        var weatherType = weatherDetails.weather[0].main.toLowerCase();
        console.log(weatherType); //<-- outputs "clouds"
        console.log(typeof weatherType); //<---- outputs string
        console.log(weatherType == "clouds"); // <-- returns false
}

为什么console.log(weatherType == "clouds");会返回false?这个类是正确的,输出也是如此,但它仍然返回false。甚至更奇怪的是有时当互联网很慢它返回true时?可能是Ajax需要慢才能检测到它吗? 。这怎么可能?

编辑: 我的代码笔:http://codepen.io/nuclearmachine/full/ZKyrVp

3 个答案:

答案 0 :(得分:0)

尝试:

var weatherType = weatherDetails.weather[0].main.toLowerCase().trim();

某处必须有空位。

答案 1 :(得分:0)

weatherDetails.weather [0] .main.toLowerCase()==&#34;云&#34;它只会返回true,请检查您的代码

示例小提琴是

$(document).ready(function(){
var details={  
   "coord":{  
      "lon":145.77,
      "lat":-16.92
   },
   "weather":[  
      {  
         "id":803,
         "main":"Clouds",
         "description":"broken clouds",
         "icon":"04n"
      }
   ],
   "base":"cmc stations",
   "main":{  
      "temp":293.25,
      "pressure":1019,
      "humidity":83,
      "temp_min":289.82,
      "temp_max":295.37
   },
   "wind":{  
      "speed":5.1,
      "deg":150
   },
   "clouds":{  
      "all":75
   },
   "rain":{  
      "3h":3
   },
   "dt":1435658272,
   "sys":{  
      "type":1,
      "id":8166,
      "message":0.0166,
      "country":"AU",
      "sunrise":1435610796,
      "sunset":1435650870
   },
   "id":2172797,
   "name":"Cairns",
   "cod":200
};
alert(details.weather[0].main.toLowerCase()=="clouds");
});

检查https://jsfiddle.net/fdxuf7qn/

答案 2 :(得分:0)

天啊,"thunderstorm"拼写"thunderstom"。现在应用程序有时正确显示的原因是因为其他天气模式拼写正确!我觉得很愚蠢但是吸取了教训。现在上面的问题以云为例,但我在计算机GAAH中测试了雷暴。