【发布时间】:2013-01-26 12:47:40
【问题描述】:
我正在尝试使用 their api 访问我的 kippt 书签。
这个 api 看起来很简单,我可以在终端中通过 curl 请求访问它。但是当我在浏览器中尝试使用 jquery ajax 进行跨域 jsonp 请求时,我收到了 401 UNAUTHORIZED 错误。
这是我的代码:
var authconfig = {
api_url: 'https://kippt.com/api/',
username: 'amit_e',
password: '*****'
}
$.ajax({
url: authconfig.api_url + 'lists',
username: authconfig.username,
password: authconfig.password,
dataType: 'jsonp',
async: false,
type: 'GET'
}).done(function(data){
console.log(data);
}).fail(function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
});
我在一个简单的 python 服务器上使用 jquery 1.9 处理 http://localhost:3501。我没有使用 jsonp 的经验。所以请帮我取回json数据。返回的数据应如下所示:
{
"meta": {
"limit": 20,
"next": "/api/clips/?limit=20&offset=20",
"offset": 0,
"previous": null,
"total_count": 33
},
"objects": [
{
"id": 15,
...
},
...
]
}
更新:
在我的 ajax 请求中添加 async: false 作为选项让我恢复了数据。有人知道为什么吗?
【问题讨论】:
-
您应该检查您的凭据。另外,如果我记得正确将
dataType设置为jsonp将自动添加callback参数。您是否在浏览器的“网络”选项卡中检查了请求的形式? -
@Alexander 仔细检查了我的信誉-不起作用-同样的错误。
-
您能否说明您在哪里处理从服务器返回的
data?我相信你没有正确使用回调 -
@Alexander 我已更新代码以反映 api 吐出数据的点。但现在我想知道为什么需要
async: false.. -
按您现在的方式试用代码,删除
async选项。使用console.log(data),而不是像以前那样使用console.log('done')。这仍然有效吗?
标签: jquery ajax api cross-domain