gpt4 book ai didi

javascript - 通过ajax调用多个脚本。脚本 2 应仅在脚本 1 执行完毕后调用

转载 作者:行者123 更新时间:2023-11-30 10:41:41 24 4
gpt4 key购买 nike

我有 4 个脚本,我想通过 ajax 一个接一个地调用它们。

我只想在 script_1 完成执行后调用 script_2

这意味着首先我想在ajax中调用script_1,在其各自的div中显示script_1执行的结果,然后调用第二个脚本,在第二个div中显示其结果等等。

目前我正在做的是在 onreadystatechange() 函数中创建一个新的 ajax 调用(以嵌套方式)。

伪代码如下:

var script1_ajax = new XMLHttpRequest();

script1_ajax.onreadystatechange=function() {
if (script1_ajax.readyState==4 && script1_ajax.status==200) {

document.getElementById('result').innerHTML = script1_ajax.responseText;
//create second ajax request and call it
//similarly create two more nested ajax calls and call it
}
}

我认为这不是正确的做法。请建议如何以不太复杂的方式执行此操作。

最佳答案

两个词:抽象和回调:

//abstract the AJAX code
function ajax(url,data,callback){
var xhr = new XHR(...
//the rest of the AJAX setup here
xhr.onreadystatechange=function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText); //execute callback
}
}
xhr.send();
}

function script1(){
//call ajax
ajax('test1.php','somedata',function(returndata){
//this callback gets executed when ajax is done
document.getElementById('result').innerHTML = returndata;
//execute next
script2();
});
}

function script2(){
ajax('test1.php','somedata',function(returndata){
document.getElementById('result').innerHTML = returndata;
script3();
});
}

function script3(){
//and so on...
}

script1(); //execute first

另一方面,您可以使用 jQuery.ajax ,这看起来几乎是一样的:

function script1(){
$.get('url','data',function(data){
$('#result').html(data);
script2();
});
}

function script2(){
$.get('url','data',function(data){
$('#result').html(data);
script3();
});
}

function script3(){
//and so on
}

script1(); //execute first

关于javascript - 通过ajax调用多个脚本。脚本 2 应仅在脚本 1 执行完毕后调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10703316/

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