jquery - 成功函数异步问题的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
});
}
解决方案
我最终用 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;
}
推荐阅读
- html - 通过网络浏览器单击按钮打开移动相机
- crystal-reports - 如何使用水晶报表图形位置中的基本目录定位图像
- .net - 在 Blazor 和 MVC 中渲染视图
- java - 尝试使用 Spark 数据集 (Java) 查找在 2 个文件之间删除的记录时结果不一致
- jquery - JQuery .click 函数在 Rails 中不起作用(有许多可能不相关的错误)
- ssh-tunnel - 从 tableau desktop 和 tableau server 连接 Aurora Severless
- java - Tutology ( DNF ) 和Contradiction ( CNF ) 方法
- python-3.x - 如何安装底图,出现错误
- r - 将前面和后面的单词连接到匹配 R 中条件的单词
- c++ - 在 MacOS 上使用 CLion 编译 32 位 C++ 程序