jquery - 为什么我的jquery延迟处理错误和jsonp数据不起作用?

标签 jquery ajax error-handling deferred

我只是想找出deferred api,并将这个不错的示例代码与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 error的情况。

我想使用我的自定义错误处理程序来处理该错误,但这似乎根本没有被触发。我究竟做错了什么?我是否误解了api?如何编写适当的Ajax错误处理程序请求?

最佳答案

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

error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event.



您可以尝试使用超时来触发错误回调,因此,基本上,我们为请求提供了一定的时间,并且当时间到期时,我们假设请求失败。
$.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 */
})

关于jquery - 为什么我的jquery延迟处理错误和jsonp数据不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14941038/

相关文章:

c# - 'ExecuteNonQuery : CommandText property has not been initialized' beginner here

jquery - knockout 加载数据非常缓慢

php - ajax 代码中的 Javascript 使用

c - 区分 C 中的客户端错误和程序员错误

node.js - uncaughtException无法捕获引发的错误

php - 没有 XMLHttpRequest() 对象的 Ajax 方法

javascript - 如何干燥我的 jQuery 代码并使其更具可读性/可维护性?

jquery - fadeOut 不会删除元素

javascript - jQuery clone div 每次点击

javascript - 在动态创建的元素上进行事件绑定(bind)?