处理嵌套 ajax 请求的正确方法

Proper way handling nested ajax request

本文关键字:方法 请求 嵌套 ajax 处理      更新时间:2023-09-26

我想知道是否有任何适当的方法可以防止 ajax 请求在同时调用其中许多错误(同步或异步)时传递随机 404/500 错误

例如,一个简单的HTML表格,其中包含一些行和列,以显示500-800人的列表以及一些数据

好:

  1. 通过从后端选择(带有组织单位的 html 表单)获取 ppl,并将结果列表写入表的第一列
  2. 通过每个人的 personId 获取每个人的事件(第一个请求的结果)
  3. 获取每个人的属性
  4. 获取每个人的角色
  5. 根据每个人的个人属性、角色和事件,从后端获取计算的内容。

伪代码:

function createTableData(){
  var selected;
  var personIds;
 //get personIds by selection and write them into table
 object.executeJSONRequest(...,
        {   _ts: new Date().getTime(),
            input: selected
        },function(data) {
                   // write result into table
                   // fill resourceIds with result param
        },..);
  getEvents(personIds);
  getAttribtues(personIds);
  getRoles(personIds);
  calculateStuff(personIds);
}

function getEvents(personIds){
   object.executeGetRequest('...',
        {   _ts: new Date().getTime(),
            ppl: personIds
        },function(data) {
                   //add result to table
        }
}
function getAttributes(personIds){...}  //and so on..

如果我连续调用所有这些方法,我有时会在加载属性时收到随机错误,有时在加载角色时,有时一切正常。

如果我称它们嵌套在每个 Ajax 成功块中,例如

function createTableData(){
     object.executeJSONRequest(...
            {   _ts: new Date().getTime(),
                input: selected
            },function(data) {
                       getEvents(..);
                    });
 }
function getEvents(..){
  object.executeGETRequest(...
            {   _ts: new Date().getTime(),
                input: selected
            },function(data) {
                       getAttributes(..);
                    });
 }

function getAttributes(..){  ...,function(data){ getRole(..)});  and so on

一切正常。如果我尝试使用类似的东西的解决方案

 document.ajaxStart/Stop(function(){  //if table columns i expected are filled do next}

我必须检查所有必要的表格列是否已经填充了数据。

有什么真正合适的解决方案,我只是想不起来吗?(jQuery 版本 1.2/IE V7-8 ^^)

"如果可能的话,更新jquery和ie版本"

首先,为什么要在单个进程中调用多个服务器调用。

最好将所有

进程合并到一个请求和响应周期中,在 java 代码中对数据进行所需的处理。不要带着请求和回应来回走动。

你可以使用jquery ajax的任何方式,它返回ajax调用的状态。

     $.post("url",function(result,status){{
            if(status == success){
    //continue....
    }else{
          alert("Sorry something went wrong");
         }
      }});

像这样检查所有请求天气它成功完成。

我强烈建议您考虑将所有 ajax 调用合并到一个请求中。