1

我只是想弄清楚deferredapi 并将这个很好的示例代码与 twitter 搜索 api 一起使用:

var getTweets = function(q) {
    return $.ajax({
        url: 'http://search.twitter.com/search.json?q=' + encodeURIComponent(q),
        dataType: 'jsonp'
    })
};

var getTheDay = function(date){
    var date = new Date(date);
    return date.getDay();
}

var parseTweetData = function(data){
    $.each(data.results, function(index, tweet){
        console.log(tweet.text 
        + ' from ' + tweet.from_user_name 
        + ' at ' + getTheDay(Date.parse(tweet.created_at) * 1000));
    });
}

var parseError = function(error, xhr) {
    alert('failed')
};

$.when(getTweets(' martin')).then(parseTweetData, parseError);

把结果拿回来就好了。问题来自 twitter 返回403 错误的情况。

我想用我的自定义错误处理程序处理该错误,但这似乎根本没有被触发。我究竟做错了什么?我误解了api吗?如何编写正确的 ajax 错误处理程序请求?

4

1 回答 1

3

根据 $.ajax 文档,jsonp 请求不会调用错误处理程序,因此它可能也不会调用延迟。

error
类型:Function(jqXHR jqXHR, String textStatus, String errorThrown)
请求失败时调用的函数。该函数接收三个参数:jqXHR(在 jQuery 1.4.x 中,XMLHttpRequest)对象,一个描述发生的错误类型的字符串和一个可选的异常对象(如果发生)。第二个参数(除了 null)的可能值是“timeout”、“error”、“abort”和“parsererror”。发生 HTTP 错误时,errorThrown 会接收 HTTP 状态的文本部分,例如“未找到”或“内部服务器错误”。从 jQuery 1.5 开始,错误设置可以接受一个函数数组。每个函数都会被依次调用。注意:跨域脚本和 JSONP 请求不调用此处理程序。

you can try using a timeout to trigger an error callback, so basically we are giving the request some amount of time to be made and when the time expires we assume the request failed.

$.ajax({
    url: 'http://search.twitter.com/search.json?q=' + encodeURIComponent(q),
    dataType: 'jsonp',
    timeout: 5000 /* 5 seconds timeout, plenty of time for the request to complete */
})
于 2013-02-18T16:45:04.130 回答