Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.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 $.ajax从外部api返回数据,但$.getJSON抛出错误_Jquery_Ajax_Api_Getjson - Fatal编程技术网

Jquery $.ajax从外部api返回数据,但$.getJSON抛出错误

Jquery $.ajax从外部api返回数据,但$.getJSON抛出错误,jquery,ajax,api,getjson,Jquery,Ajax,Api,Getjson,我在使用.getJSON JQuery方法从外部API*返回数据时遇到问题,但是.ajax方法工作正常 将此代码与.ajax一起使用对我来说很有用: var apiKey = 'myKey', requestURL = 'https://api.propublica.org/congress/v1/115/senate/members.json'; $.ajax({ url: requestURL, type: "GET", dataType

我在使用.getJSON JQuery方法从外部API*返回数据时遇到问题,但是.ajax方法工作正常

将此代码与.ajax一起使用对我来说很有用:

var apiKey = 'myKey',
requestURL = 'https://api.propublica.org/congress/v1/115/senate/members.json'; 


        $.ajax({
     url: requestURL, 
     type: "GET",
     dataType: 'json',
     headers: {'X-API-Key': apiKey }
   }).done(function(data){
   console.log(data)
   });
使用$.getJSON对我不起作用:

var apiKey = 'myKey',
requestURL = 'https://api.propublica.org/congress/v1/115/senate/members.json'; 


    $.getJSON(requestURL + '?callback=?', {
        'X-API-Key': apiKey
    }, function(data){
    console.log(data);
    });
唯一的区别是我在url中添加了“?callback=?”,正如文档和一些帖子/教程所说的那样,这样它将返回JSONP。我试着更改url,看看是否可以修复它,但几个小时后,我无法让它工作

我在控制台中得到的错误如下:

GET net::ERR_中止

如果我从getJSON示例的url中去掉“?callback=?”,我会得到上面的消息以及这个额外的错误消息:

加载失败:请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“”。响应的HTTP状态代码为401

我不明白为什么这不起作用,因为getJSON应该是我上面的.ajax调用的简写


你知道为什么.getJSON不起作用,但是.ajax会起作用吗

您不能使用getJSON设置http头,您的API似乎要求它允许CORS。虽然您可以使用设置标题,但我不推荐使用它,因为所有后续ajax调用都将使用这些设置

jQuery.ajaxSetup({headers: {'X-API-Key': apiKey }});
$.getJSON(requestURL, function(data){
    console.log(data);
});

我认为问题可能是您无法将头传递到$.getJSON

可能重复: