我正在开发一个PHP应用程序,它使用ajax在页面中加载组件。更重要的是,这些模块/组件应该以这样的顺序加载:如果前一次加载失败,则随后的加载也将失败。
换句话说,页面加载、进行ajax调用并接收json编码的响应。如果响应是“成功”,它进行第二个调用并接收另一个json响应。同样,如果第二个响应是“成功”,它将进行第三个调用,依此类推。这应该会发生大约8次,在这一点上,页面被认为完全加载。
如果在加载期间,假设第三个请求收到响应"FAIL",则来自4-8的请求将被放弃,并抛出一条错误消息。
我现在实现这一点的方法是进行第一个调用,等待响应,然后在第一个调用中进行第二个调用。
为了将其放在参考中,下面是代码的一部分:
$.get(WEB_ROOT+'/process/createKeywords', {}, function(keywordsResponse) {
$('#createKeywords').parent().children(0).children(0).hide();
if (keywordsResponse.RESPONSE == "SUCCESS") {
$('#createKeywords').html(img);
$('#getTraffic').parent().children(0).children(0).show();
$.get(WEB_ROOT+'/process/getTraffic', {}, function(trafficResponse) {
$('#getTraffic').parent().children(0).children(0).hide();
if (trafficResponse.RESPONSE == "SUCCESS") {
$('#getTraffic').html(img);
$('#getGoogleResults').parent().children(0).children(0).show();
$.get(WEB_ROOT+'/process/getGoogleResults', {}, function(googleScrapeResponse) {
$('#getGoogleResults').parent().children(0).children(0).hide();
if (googleScrapeResponse.RESPONSE == "SUCCESS") {
$('#getGoogleResults').html(img);
$('#resortResults').parent().children(0).children(0).show();正如你可以想象的那样,这很快就会变得复杂和丑陋。有没有人对我如何做这样的事情有什么建议?
发布于 2012-03-02 04:58:46
//setup an object to store the necessary info for each AJAX call
var setup = [
{
url : WEB_ROOT + '/process/createKeywords',
//the callback will be run before the next AJAX request is made
callback : function (keywordsResponse) {
$('#createKeywords').parent().children(0).children(0).hide();
if (keywordsResponse.RESPONSE == "SUCCESS") {
$('#createKeywords').html(img);
$('#getTraffic').parent().children(0).children(0).show();
}
}
},
{
url : WEB_ROOT + '/process/getTraffic',
callback : function () {
$('#getTraffic').parent().children(0).children(0).hide();
if (trafficResponse.RESPONSE == "SUCCESS") {
$('#getTraffic').html(img);
$('#getGoogleResults').parent().children(0).children(0).show();
}
}
}
];
//setup a function that recursively calls itself when the current AJAX request comes back successfully
function doAJAX(index) {
var val = setup[index];
$.getJSON(val.url, function (serverResponse) {
//run the specified callback for this AJAX request
val.callback(serverResponse);
//now check if the response is "SUCCESS" and make sure that another AJAX request exists in the `setup` object
if (serverResponse.RESPONSE == 'SUCCESS' && typeof setup[(index + 1)] != 'undefined') {
//since the last AJAX request was a success and there is another one set, run it now
doAJAX(index + 1);
}
});
}
//run the first AJAX request by passing in zero (index)
doAJAX(0);这只允许您为连续的AJAX请求设置必要的变量。与每个url关联的callback将在运行下一个AJAX请求之前运行。
发布于 2012-03-02 05:04:43
您可能需要考虑将其设置为动作对象的集合。每个对象都有一个URL、一个pre-action、一个post-action和一个success操作。设计一个函数,该函数弹出第一个操作,执行它的预操作,然后执行AJAX调用。在AJAX调用返回时,它执行后期操作,检查是否成功,如果成功,则执行成功操作,并使用其余任务调用自身。这样的系统将是相当灵活的,可以适应任何数量的任务。
https://stackoverflow.com/questions/9523834
复制相似问题