Jquery:$ ajax - 即使成功请求也会调用错误函数

时间:2011-12-23 10:36:14

标签: jquery ajax api

我正在向API(instapaper)发送ajax请求,我已经能够成功发出请求,即我已成功发送到instapaper的链接并收到了正确的状态代码 - 201。 但是,将调用错误回调函数而不是成功函数。我认为这是因为我设置了我的请求的方式。例如。它希望以不同的格式进行响应。

请求功能:

$("#instapaper").click(function() {
    $.ajax({
        type: 'GET',
        dataType: 'jsonp',
        url:'http://www.instapaper.com/api/add',
        data: {"url": ref , "username": "<%= current_user.instapaper_user %>", "password": "<%= current_user.instapaper_pass %>" },
        context: document.body,
        error: function() { 
          alert('There was an error!');
        },
        success: function() {
          alert('Page sent');
        },
      })
    });

我已经尝试使用代码201的状态代码回调,但这也不起作用。 任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:1)

看起来instapaper APIjsonp作为回调函数名称,但jQuery中的默认值为callback

我建议您将jsonp: 'jsonp'添加到您的ajax对象中,看看它是否有效:

$.ajax({
    type: 'GET',
    dataType: 'jsonp',
    url:'http://www.instapaper.com/api/add',
    data: {"url": ref , "username": "<%= current_user.instapaper_user %>", "password": "<%= current_user.instapaper_pass %>" },
    context: document.body,
    error: function() { 
      alert('There was an error!');
    },
    success: function() {
      alert('Page sent');
    },
    jsonp: 'jsonp'
});

答案 1 :(得分:0)

Per this discussion,如果您打算直接尝试处理状态代码,我认为您需要删除您的成功功能。

您是否尝试使用以下状态码选项:

statusCode: {
    200:function() { alert("200"); },
    201:function() { alert("201"); }
}

答案 2 :(得分:0)

根据instapaper doco,指定jsonp回调的参数应该被称为“jsonp”,而jQuery默认为“回调”。您可以通过指定“jsonp”选项来覆盖它:

$("#instapaper").click(function() {
    $.ajax({
        type: 'GET',
        dataType: 'jsonp',
        jsonp : 'jsonp',  // <---------------------NEW BIT HERE
        url:'http://www.instapaper.com/api/add',
        data: {"url": ref , "username": "<%= current_user.instapaper_user %>", "password": "<%= current_user.instapaper_pass %>" },
        context: document.body,
        error: function() { 
          alert('There was an error!');
        },
        success: function() {
          alert('Page sent');
        },
      })
    });

有关详细信息,请参阅jQuery doco

相关问题