2010-10-13 60 views
2

如何從成功函數中的JQuery.Ajax()返回多個值?來自ASP.NET的多個返回值的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 

它用起來很獨特返回的字符串,但數組不工作:(

+1

是您的實際的WebMethod返回JSON結果?根據你發佈的代碼,我不認爲它是。 – CodingGorilla 2010-10-13 17:38:41

回答

8

將其更改爲msg.d[0]

Wirting msg.a是完全錯誤的;方法的返回值與變量名無關。

但是,出於安全原因,ASP.Net將JSON對象封裝在d屬性中,因此您需要編寫msg.d來訪問該數組。

0

我得到了解決方案!

我只是用msg.d[0]代替msg.a[0]

1

,我自己用response.d返回逗號的前格式化全陣列。[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 

感謝