【发布时间】:2021-04-30 22:43:40
【问题描述】:
其中一个将连接到 php 页面并获取一些数据,而我的另一个函数将使用第一个函数收集的新数据更改一些 html 代码。
例如这是我的代码:
var $data;
firstFunction(){
$.post("index.php",{},function(data){$data=data;});
}
secondFunction(){
$("body").empty().append($data);
}
firstFunction();
secondFunction();
所以在代码中,如果我们运行它,它会开始收集数据,但在完成收集数据之前,它会运行第二个函数,这是不正确的,它必须在第一个函数完成类似这样的事情后运行第二个函数:
$.when(firstFunction()).done(function(){secondFunction();});
但它也不起作用,我知道有一种叫做异步的东西,但我想知道是否还有其他方法可以在不改变功能的情况下这样做,如果可能的话,请给我一个异步的例子。
我也不想改变功能,我的意思是我知道我可以这样做:
var $data;
firstFunction(){
$.post("index.php",{},function(data){$data=data;secondFunction();});
}
secondFunction(){
$("body").empty().append($data);
}
firstFunction();
正如您在新代码中看到的那样,第二个函数将在第一个权限完成后运行,但我不能也不想这样做功能多,更换主题需要很长时间。
非常感谢。
【问题讨论】:
-
据我所知这是唯一可行的方法
标签: javascript jquery function async-await .post