gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:08:07 25 4
gpt4 key购买 nike

我只是想找出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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com