首页 > 解决方案 > 成功函数异步问题的jQuery回调

问题描述

我通过 Ajax 获取一些 XML,并通过调用成功的函数来处理它。

从成功函数 (handleHousestark) 中,我正在检查 XML 并调用另一个函数 (getJonSnow) 以添加一些额外的数据。如果我将 getJonSnow 设置为 async :false,一切正常。没有它是行不通的。

$( document ).ready(function() {
  $( "#button" ).click(function() {
    $.ajax({
      url: "test_php.php?function=getmain",
      cache: false,                           
      success: handleHousestark                       
    });
  });
});

function handleHousestark(html) {   
  var feature="";
  var xml = html;
  xmlDoc = $.parseXML( xml );
  $xml = $( xmlDoc );

  $($xml).find( "features" ).children().each(function(index) {
    var attributevalue = $(this).attr('value');
    var attributeunittype = $(this).attr('type');     
    var attributecode = $(this).attr('code');  
    if(attributeunittype!="Valuelist") {
      feature=feature+"<B>"+attributevalue+"</B><BR/>";
    }

    if(attributeunittype=="Valuelist") {
      values = getJonSnow(attributecode,function(res) { 
        ///THIS WORKS WITH getJonSnow on async false, otherwise doesn't work.           feature=feature+"<B>"+res+"</B><BR/>";
      });
    }   
  }); 
  $("#content").html(feature);
}

function getJonSnow(attributecode,callback) {
  $.ajax({
    url: "test_php.php?function=getvalues",
    cache: false,     
    success:  callback                  
  });
}

标签: jqueryfunctionasynchronouscallback

解决方案


我最终用 await 和 async 完成了这个工作,效果非常好。我已经有几年没有做过 ajax 了,而且在最新的方法论上有点落后。

下面的示例,我没有测试这个示例,但希望其他人得到 jist。

$( document ).ready(function() {
  $( "#button" ).click(function() {
    $.ajax({
      url: "test_php.php?function=getmain",
      cache: false                      
    })
    .done(function(data)
                        {

                            handleHousestark(data);

                        })  ;
  });
});

async function handleHousestark(html) {   
  var feature="";
  var xml = html;
  xmlDoc = $.parseXML( xml );
  $xml = $( xmlDoc );

  $($xml).find( "features" ).children().each(function(index) {
    var attributevalue = $(this).attr('value');
    var attributeunittype = $(this).attr('type');     
    var attributecode = $(this).attr('code');  

    values=await getJonSnow(attributecode);

    if(attributeunittype!="Valuelist") {
      feature=feature+"<B>"+attributevalue+"</B>"+values+"<BR/>";
    }


    }   
  }); 
  $("#content").html(feature);
}

async function getJonSnow(attributecode) {

  const  tmp = $.ajax({
    url: "test_php.php?function=getvalues",
    cache: false               
  });

  return  tmp;
}

推荐阅读