JSON data not being returned - JQuery AJAX

前端 未结 5 1526
夕颜
夕颜 2021-01-26 06:10

I am testing out this script which retrieves the weather data from the URL. But for some reason I am not getting the response back. I have enabled cross-site. Can someone point

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-26 06:44

    You need to set the dataType in the ajax call to "jsonp". Check out this jsFiddle. I found the answer (essentially) from this SO post.

    $("button").click(function(){
       $.ajax({
           type:"GET",
           url:"http://api.openweathermap.org/data/2.5/weather?q=London",
           dataType : "jsonp",
           success:function(result){
               console.log(result);
                $("#div1").html(result['name']);
           },
           error: function(xhr, status, error) {
               console.log(status);
           }
         });
    });
    

    To give a little more background on why this is needed:

    This is basically a way to get around browsers and cross-site protection (per my understanding--it looks like suspicious behavior to browsers). Nowadays, server owners can allow cross-site origin requests (CORS), but if the server owner (openweathermap in this case) does not, you can still request data via jsonp (see this wikipedia entry for more details: en.wikipedia.org/wiki/JSONP)

提交回复
热议问题