我有一个 html 元素 (elem1
) 和 2 个隐藏和显示 elem1< 的 JS 函数 (
分别。这些 JS 函数进行单独的 ajax 调用,func1
, func2
)/func2
在内部调用 func1
。
问题:我需要调用 func2
,它在内部调用 func1
。调用 func1
隐藏 elem1
。调用func1
后,我想show
elem1
。但是这个 show
不工作。
JSFiddle:https://jsfiddle.net/46o93od2/21/
HTML:
<div id="elem">
Save ME
</div>
<br/>
<button onclick="func1()" id="func1">Try Func1</button>
<button onclick="func2()" id="func2">Try Func2</button>
JS:
function func1() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
$('#elem').hide();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
func1();
$('#elem').show();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
最佳答案
让 func1
接受一个回调函数,告诉它在收到响应后要做什么。 func2
可以传递一个显示元素的函数。
function func1(callback) {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
if (callback) {
callback();
} else {
$('#elem').hide();
}
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
func1(function() {
$('#elem').show();
});
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
关于javascript - show() 覆盖多个 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36875872/