请参考下面的代码:
function createXMLHttpRequestObject() {
// will store the reference to the XMLHttpRequest object
var ajaxRequest;
// create the XMLHttpRequest object
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// return the created object or display an error message
if (!ajaxRequest) alert("Error creating the XMLHttpRequest object.");
else return ajaxRequest;
}
function ajax_update() {
var ajaxRequest = createXMLHttpRequestObject();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState != 4){
...
}
if(ajaxRequest.readyState == 4){
//process JSON data
}
}
}我正在尝试监视/侦听来自ajax_update()函数外部的ajaxRequest.readyState值。ajax_update()在单击按钮时触发。
我的目标是在函数ajax_update()之外仅在完成所有Ajax调用时触发另一个JS函数,即ajaxRequest.readyState==4。
对于ex:
<input type='button' value='SEND QUOTE' onclick=\"ajax_update(some params); function_that_fires_when_readystate_is_completed();\">有什么想法吗?
提前谢谢你!
发布于 2012-06-12 03:42:50
从全局上定义这一点
var requestCounter = 0;然后
function ajax_update() {
var ajaxRequest = createXMLHttpRequestObject();
//after calling request.open();
requestCounter++;
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState != 4){
requestCounter--;
//error code here
}
if(ajaxRequest.readyState == 4){
//process JSON data
requestCounter--;
}
if (requestCounter == 0)
onAllRequestComplete();
}
}
function onAllRequestComplete(){
// code that have to run when all requests have been completed
}希望能有所帮助。
发布于 2012-06-12 03:51:21
使用回调。
JS
function ajax_update(callback) {
var ajaxRequest = createXMLHttpRequestObject();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
callback();
}
};
xmlhttp.open(...);
xmlhttp.send(null);
}HTML
<input onclick="ajax_update(function_that_listens_to_readyState);">发布于 2012-06-12 03:58:13
ajaxRequest1.onreadystatechange = function(){
if(ajaxRequest.readyState != 4){
...
}
if(ajaxRequest.readyState == 4){
//process JSON data
firstIsReady = true;
check();
}
}
ajaxRequest2.onreadystatechange = function(){
if(ajaxRequest.readyState != 4){
...
}
if(ajaxRequest.readyState == 4){
//process JSON data
secondIsReady = true;
check();
}
}
function check() {
if (firstIsReady && secondIsReady) {
//both ajax calls completed
}
}差不多吧。它真的很难看,但是如果不知道你到底想要做什么,我不能给你一个更好的方法。
https://stackoverflow.com/questions/10986323
复制相似问题