如何在OpenWeatherAPI中使用JSONP GET请求? [英] How to use JSONP GET request with the OpenWeatherAPI?

查看:142
本文介绍了如何在OpenWeatherAPI中使用JSONP GET请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 OpenWeatherAPI 使用JQuery执行获取JSONP数据get请求.我的查询结构如下:

I am trying to use the OpenWeatherAPI to perform get JSONP data using a JQuery get request. I have structured my query like this:

function getWeather(callback) {
    var weather = 'http://openweathermap.org/data/2.1/find/city?lat=13.3428&lon=-6.2661&cnt=10&jsoncallback=?';
    jQuery.getJSON(weather, callback);
}

// get data:
getWeather(function(data){
    console.log('weather data received');
});

我收到以下错误消息:

SyntaxError:无效标签

SyntaxError: invalid label

但是,正在返回数据,因为我可以在Firebug中单击它,因此可以得到预期的结果.我正在客户端执行所有操作,所以也许我的JSONP请求有一个基本错误.在该主题上进行搜索还表明,返回的数据可能是JSON形式的,而不是JSONP,但是我不确定有什么区别.

However, the data is being returned as I can click on it in Firebug and it gives me the expected results. I am performing this all on the client-side so perhaps I have a basic mistake on my JSONP request. Searching on this topic also suggested that the returned data may be in JSON form and not JSONP, but I am unsure of what the difference is.

推荐答案

如果使用的是jQuery,则可以使用内置的JSONP功能为您处理回调.只需使用$ .ajax即可,

If you are using jQuery, you can use the built in JSONP functionality to handle the callback for you. Just use $.ajax instead, as so:

function getWeather(callback) {
    var weather = 'http://openweathermap.org/data/2.1/find/city?lat=13.3428&lon=-6.26612&cnt=10';
    $.ajax({
      dataType: "jsonp",
      url: weather,
      success: callback
    });
}

// get data:
getWeather(function (data) {
    console.log('weather data received');
    console.log(data.list[0].weather[0].description);
});

jsFiddle: http://jsfiddle.net/wCjW3/1/

jsFiddle: http://jsfiddle.net/wCjW3/1/

参考: http://api.jquery.com/jQuery.ajax/

这篇关于如何在OpenWeatherAPI中使用JSONP GET请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆