jquery - 轮询、Ajax 和状态回调
问题描述
我想使用 jQuery 和 AJAX 不断地轮询 URL,直到我得到 200 状态代码响应。URL 指向提供文件的 REST API。理想情况下,我会得到其他状态代码,我将再次调用 URL,只有当返回 200 时,我才会离开递归并做其他事情。
对于递归,我需要保留var jsonobj
.
从 ajax 调用中获取响应,我惨遭失败。我试图复制这个。早些时候我试图让 jsonobj 在 statusCode 中处理,但它没有遍历。
var jsonobj = 9189829182 // (job-id) returned from an earlier call which is not depicted here
function doPoll(jsonobj) {
function pollQuery(p_data, state) {
jQuery.ajax({
headers: {
"access-token": "67e9489669217"
},
type: 'GET',
url: 'https://someurl/classifier/' + jsonobj["id"],
crossDomain: true,
statusCode: {
200: function(p_data, state) {
console.log("data available");
},
204: function(p_data, state) {
console.log("processing");
}, // this shows on console, but how do we get the state out of here?
404: function(p_data, state) {
console.log("resource not found / not available");
}
}
})
}
console.log("jsonobj :" + jsonobj);
pollQuery(function(response) {
console.log("response :" + response); // not working
console.log("state :" + state); // not working
});
}
解决方案
To fix this you need to correct the callback argument, as you're overriding it in each of the statusCode
handler functions. In addition, you can simplify the logic by retrieving the status code from the jqXHR object passed to success
instead of having to write code for every possible status code. This will also make the recursion more straightforward. Try this:
function doPoll(obj) {
function pollQuery(callback) {
jQuery.ajax({
headers: {
"access-token": "67e9489669217"
},
type: 'GET',
url: 'https://someurl/classifier/' + obj["id"],
crossDomain: true,
success: function(data, status, xhr) {
if (xhr.status !== 200) {
setTimeout(function() {
pollQuery(callback); // recurse after 10 second delay
}, 10000);
// if required you can handle the messages shown for 204 and 404 states here...
} else {
callback && callback(data); // 200 received, execute callback function
}
}
})
}
pollQuery(function(response) {
console.log("response :" + response);
});
}
However I'd strongly suggest you do not follow the pattern of AJAX polling as it doesn't scale and, long term, causes more problems than it solves. I'd strongly suggest you follow the observer pattern for this instead by using Websockets. There are lots of resources available showing how to do this when you search.
推荐阅读
- visual-studio - Visual Studio 安装程序,在复制文件之前执行自定义操作
- r - 从 md 文件创建小插图,而不是 Rmd
- javascript - 如何使 SSL Websocket 与 Django 通道一起工作
- python - Seaborn 错误:找不到“高度”,它去哪儿了?
- javascript - 具有异步加载选项卡内容的 Angular 选项卡组。内容必须是另一个组件
- python - Python,WebScraping天气值
- java - googleCast getMediaInfo() 每次返回空值
- c++ - Ncurses - 在初始化我的窗口之前等待按钮按下的空白窗口
- angular-material - Mat 图标浮动在输入的右侧,并且不以键入的文本为中心
- selenium - microsoft edge 和 safari 浏览器中未识别元素