从Json URL获取数据的方法

5

第一个问题是,你正在进行跨域操作。然后,数据看起来不像JSONP格式。这样做没有任何作用。 - Joseph
3个回答

3
您可以使用JSONP来进行此类请求,但我认为您尝试访问的URL没有JSONP功能。由于您想要汇率(我猜测是根据您尝试使用的URL),您可以使用以下方法:

$(document).ready(function(){
    $.ajax({
        url: 'http://openexchangerates.org/latest.json',
        dataType: 'jsonp',
        success: function(json) {
            // Rates are in `json.rates`
            // Base currency (USD) is `json.base`
            // UNIX Timestamp when rates were collected is in `json.timestamp`        

            rates = json.rates;
            base = json.base;
            console.log(rates);
        }
    });
});

参考来源:点击此处

希望能对您有所帮助


为什么dataType是'jsonp'而不是'json'? - Green Lei

3
这应该与jQuery一起使用:
$.ajax({
  url: 'https://raw.github.com/currencybot/open-exchange-rates/master/latest.json',
  dataType: 'jsonp',
  success: function (data, textStatus, jqXHR) {
    //the variable 'data' will have the JSON object
    // In your example, the following will work:
    alert(data.disclaimer);
   error: function(jqXHR, textStatus, errorThrown) {
     //Error handling code
     alert('Oops there was an error');
   }
  }
});

1

1
getJSON不会在OP的情况下开箱即用,因为它很可能是一个跨域请求(除非OP在GitHub工作:))。您需要在URL末尾添加'callback=?'来使getJSON起作用。无论如何,我建议使用$.ajax作为最佳实践,以便可以优雅地处理错误。 - ErJab
$.getJson() 是一个简写的 Ajax 函数,参见 http://api.jquery.com/jQuery.getJSON/。 - Nagaraju Badaeni
2
是的,我知道这是$.ajax的简写形式。但在这种特殊情况下,除非你在调用getJSON时在URL中添加'&callback=?',否则它将不起作用,因为OP正在进行跨域调用。 - ErJab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接