在我的 .NET MVC Web 项目中,我使用此 javascript 在用户单击按钮时获取数据。
<script type="text/jscript">
async function firstFunction() {
var url = "/Home/CheckPrinter?printer=" + document.getElementById("printerName").value;
$.get(url, null, function (data) {
$("#msgPrinterName").html(data);
});
var e = document.getElementById("ddlViewBy");
var deviceType = e.options[e.selectedIndex].text;
var url2 = "/Home/CheckIfValidIP?input=" + document.getElementById("ipAddress").value + "&type=" + deviceType;
$.get(url2, null, function (data2) {
$("#msgIPPort").html(data2);
});
var url3 = "/Home/CheckPrintService?printer=" + document.getElementById("printerName").value;
$.get(url3, null, function (data3) {
$("#msgPrintService").html(data3);
});
};
async function secondFunction() {
await firstFunction();
console.log($("#msgPrinterName").html());
console.log($("#msgIPPort").html());
console.log($("#msgPrintService").html());
// now wait for firstFunction to finish...
// do something else
};
</script>
返回的数据将显示在这里:
<div id="alerts">
<p id="msgPrinterName">
</p>
<br />
<p id="msgIPPort">
</p>
<br />
<p id="msgPrintService">
</p>
<p id="msgButton">
</p>
</div>
我遇到的问题是,当我单击按钮两次时,我只能获取内部 HTML,但我想直接获取数据。
最佳答案
您可以使用回调来解决此问题。
function firstFunction(callback) {
....
$.get(url3, null, function (data3) {
$("#msgPrintService").html(data3);
}).done(function(){callback();});
}
function secondFunction() {
firstFunction(function(){
console.log($("#msgPrinterName").html());
console.log($("#msgIPPort").html());
console.log($("#msgPrintService").html());
}
}
你也可以使用带有回调的ajax
关于javascript - 直接处理来自 AJAX 请求的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52592880/