强制函数在使用jquery.get方法接收时显示结果

Force function to show result when they received with jquery.get method

本文关键字:方法 结果 显示 get jquery 函数      更新时间:2023-09-26

此函数使用$.get方法从asp-ashx XML文件中获取结果:

$.get("http://www.example.com/example.ashx",
                { From: txtFrom, To: txtTo, Date: txtTime },
                function (data) {
                    var arrFrom = [], arrTo = [], arrPrice = [];
                    $(data).find("F").each(function (index, item) {
                        arrFrom[index] = [];
                        arrTo[index] = [];
                        arrPrice[index] = [];
                        $(item).find("From").each(function (i, fromIndex) {
                            arrFrom[index].push($(fromIndex).text());
                        });
                        $(item).find("To").each(function (i, toIndex) {
                            arrTo[index].push($(toIndex).text());
                        });
                        $(item).find("Price").each(function (i, priceIndex) {
                            arrPrice[index].push($(priceIndex).text());
                        });
                    });
                    /**********************************************************/
                    var htmlResult = "<table style='"background-color:red;'">";
                    for (i = 0; i < arrFrom.length; i++) {
                        htmlResult += "<tr><td>" + arrFrom[i] + "</td>" +
                            "<td>" + arrTo[i] + "</td>" +
                            "<td>" + arrPrice[i] + "</td></tr>"
                    };
                    htmlResult += "</table>";
                    $('#divSearchResults').html(htmlResult);
                    /**********************************************************/
                }, "text");

但ashx需要一些时间(不可预测)来做出回应。我使用了一个功能,每5秒回忆一次,但这不是负担得起的。如何在收到响应时立即创建htmlResult?

您的示例代码是正确的,因为您定义的匿名函数在后端响应后立即启动。如果你的数据是空的,这可能意味着当你在javascript中处理数据时,数据发生了一些事情,你的后端返回了一个空的数据集,或者你的后端超时了。要检查问题是否与您的后端或数据处理有关,请尝试以下操作:

$.get("http://www.example.com/example.ashx",
    { From: txtFrom, To: txtTo, Date: txtTime },
    function (data) {
        console.log(data);
        //Or in case you don't have a developer console use alert:
        alert(data);
    }, "text");

您现在应该能够验证您确实正在获取数据。如果是这种情况,那么在解析数据时,数据会发生一些问题,您应该调试该代码,也许使用静态数据集。您还可以通过发送json编码的数据而不是明文来让您的生活变得更轻松。我不知道你会如何用你的后端做到这一点,但我相信谷歌会有所帮助。在javascript方面,您可以将最后一行更改为:

    }, "json");

然后,您可以使用一个整洁的json对象,而不是find()