Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 如何从json url获取数据_Jquery_Json - Fatal编程技术网

Jquery 如何从json url获取数据

Jquery 如何从json url获取数据,jquery,json,Jquery,Json,我想在我的网页上显示来自的数据(国家名称和货币价值)。请给我建议一种方法。使用jQuery.getJSON()函数 阅读本教程您可以使用JSONP发出此类请求,但我认为您尝试访问的url没有JSONP功能。由于您需要汇率(我猜根据您尝试使用的url),您可以使用: $(document).ready(function(){ $.ajax({ url: 'http://openexchangerates.org/latest.json', dataType

我想在我的网页上显示来自的数据(国家名称和货币价值)。请给我建议一种方法。

使用jQuery.getJSON()函数


阅读本教程

您可以使用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);
        }
    });
});
参考:

希望它有帮助

这应该适用于:


第一个问题是,您正在进行跨域操作。然后,数据看起来不像JSONP。这不会发生在任何地方。getJSON在OP的情况下都不会开箱即用,因为它很可能是一个跨域请求(除非OP在GitHub:上工作)。您需要将“callback=?”附加到URL以使getJSON工作。在任何情况下,我都建议使用$.ajax作为最佳实践,以便优雅地处理错误。$.getJson()是一个速记ajax函数。是的,我知道它是$.ajax的速记。但是在这种特殊情况下,除非在调用getJSON时将“&callback=?”添加到URL中,否则它将不起作用,因为OP正在进行跨域调用。为什么数据类型是“jsonp”而不是“json”?
$.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');
   }
  }
});