【问题标题】:Work directly with data from AJAX request直接处理来自 AJAX 请求的数据
【发布时间】:2018-10-01 14:03:24
【问题描述】:

在我的 .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,但我想直接获得数据。

【问题讨论】:

  • "async函数声明定义了一个异步函数,它返回一个AsyncFunction对象。异步函数是通过事件异步操作的函数循环,使用隐式 Promise 来返回其结果。” - 我在 firstFunction() 中看不到任何 return

标签: javascript c# model-view-controller


【解决方案1】:

你可以使用回调来解决这个问题。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多