请参阅以下代码:
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值。 按钮onlick上会触发ajax_update()。
我的目标是在函数ajax_update()之外仅在所有Ajax调用完成时触发另一个JS函数,这意味着ajaxRequest.readyState == 4.
代表:
<input type='button' value='SEND QUOTE' onclick=\"ajax_update(some params); function_that_fires_when_readystate_is_completed();\">
有什么想法吗?
提前谢谢!
答案 0 :(得分:0)
定义这个全局
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
}
希望有所帮助。
答案 1 :(得分:0)
使用回调。
function ajax_update(callback) {
var ajaxRequest = createXMLHttpRequestObject();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
callback();
}
};
xmlhttp.open(...);
xmlhttp.send(null);
}
<input onclick="ajax_update(function_that_listens_to_readyState);">
答案 2 :(得分:0)
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
}
}
这样的事情。这真的很难看,但如果不知道你想做什么,我就无法给你一个更好的方法。