【问题标题】:How do I access the kippt api using only jquery ajax?如何仅使用 jquery ajax 访问 kippt api?
【发布时间】: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


【解决方案1】:

我相信您对异步函数使用了同步方法,就像 AJAX 函数一样。错误方法的示例:

var f = function(){
    $.ajax({
        ...
    }).done(function(data){
        console.log('done');
    });
    /* data isn't available yet - data is undefined */
    return data;
};

AJAX 函数立即返回。即便如此,回应还没有到来。服务端返回数据时会触发done回调,你需要做出反应。

【讨论】:

    猜你喜欢
    • 2016-04-18
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 2010-11-26
    • 1970-01-01
    • 2014-02-15
    相关资源
    最近更新 更多