[英]Work directly with data from AJAX request
Within my .NET MVC web project I got this javascript to get data when the user clicks a button. 在我的.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>
The data returned will be displayed here: 返回的数据将显示在此处:
<div id="alerts">
<p id="msgPrinterName">
</p>
<br />
<p id="msgIPPort">
</p>
<br />
<p id="msgPrintService">
</p>
<p id="msgButton">
</p>
</div>
The problem I have is that I only get the inner HTML when I click the button twice, but I want to have the data available directly. 我遇到的问题是,当我两次单击按钮时,我仅获得内部HTML,但是我想直接获得数据。
you can use callback for this problem. 您可以使用回调来解决此问题。
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());
}
}
also you can use ajax with callback 你也可以在回调中使用ajax
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.