【问题标题】:JQuery Ajax with multiple return values from ASP.NET具有来自 ASP.NET 的多个返回值的 JQuery Ajax
【发布时间】:2011-04-24 23:49:26
【问题描述】:

如何在成功函数中从 JQuery.Ajax() 返回多个值?

我试过了:

          $.ajax({
                type: "POST",
                url: "default.aspx/myFunction",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    $("#myDiv").html(msg.a[0]);
                    $("#myDiv2").html(msg.a[1]);
                }
            });

这里是我的 ASP.NET 页面:

<WebMethod()> _
Public Shared Function myFunction() As Array

     Dim a() As String
     a(0) = "value 1"
     a(1) = "value 2"

     Return a

End Function

它只适用于唯一的返回字符串,但数组不起作用:(

【问题讨论】:

  • 您的 WebMethod 是否真的返回了 json 结果?根据您发布的代码,我认为不是。

标签: asp.net jquery ajax webmethod


【解决方案1】:

对于我自己,我使用 response.d 返回以逗号的 ex.[1,2,3] 格式格式化的完整数组。接收个人,同上(response.d[0])。使用 WebMethod 将值作为 List(Of Strings) 返回到 AJAX。

                var Str = {};
                Str.StrVal = 'Test1';
                Str.StrVal2 = 'Test2';
                Str.StrVal3 = 'Test3';
                Str.StrVal4 = 'Test4';
                $.ajax({
                    type: "POST",
                    url: "VB.aspx/GetString",
                    data: '{Str: ' + JSON.stringify(Str) + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert("User has been added successfully." + response.d);
                        //window.location.reload();
                        //window.data("kendoWindow").close();
                        Str.StrVal = response.d[0]//response.d
                        //AddTab(response.d)
                        GetTabs(Str.StrVal)
                    },
                    error: function (response) {
                        alert(response.d)
                    }
                });

这里是 Web 方法,很抱歉简短的变量描述。只是一个样本。

<WebMethod()> _
<ScriptMethod()> _
Public Shared Function GetString(Str As SendString) As List(Of String)
    Dim a As New List(Of String)
    a.Add("1")
    a.Add("2")
    Return a
End Function

谢谢

【讨论】:

    【解决方案2】:

    我找到了解决方案!

    我只是使用msg.d[0] 而不是msg.a[0]

    【讨论】:

      【解决方案3】:

      将其更改为msg.d[0]

      msg.a是完全错误的;方法的返回值与变量名无关。

      但是,出于安全原因,ASP.Net 将 JSON 对象包装在 d 属性中,因此您需要编写 msg.d 才能访问该数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-14
        • 2014-04-10
        • 2019-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-01
        • 1970-01-01
        相关资源
        最近更新 更多