2

如何在成功函数中从 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

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

4

3 回答 3

8

将其更改为msg.d[0].

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

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

于 2010-10-13T17:40:06.127 回答
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

谢谢

于 2014-09-05T18:49:42.520 回答
0

我得到了解决方案!

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

于 2010-10-13T17:40:16.783 回答