2011-07-22 50 views
1

我想从Ajax调用中返回多个值。所以我修改基于此页面上的我的代码Jquery return multiple values in ajax calljson-jquery返回未定义的多个值在ajax调用

$.ajax({ 
    type: "POST", 
    contentType: "application/json; charset=utf-8", 
    url: "AJAX_custom_function.aspx/AJAX_GetFullName", 
    data: '{userid: "' + arguments.Value + '"}', 
    dataType: "json", 
    async: false, 
    success: function (data) { 
     alert(data); 
     alert(data.fullname);  
    }, 
    error: function (httpRequest, textStatus, errorThrown) { 
     alert("status=" + textStatus + ",error=" + errorThrown); 
    }  
}); 

'警报(数据)' 返回{ “全名”: “乔”, “成功”: “真正的”}

但“警报(数据.fullname)'返回undefined。正确的值应该是Joe

我错过了什么吗?任何建议非常感谢。

AJAX_GetFullName

<System.Web.Services.WebMethod()> _ 
Public Shared Function AJAX_GetFullName(ByVal userid As String) As Object 

    Dim isValid As Boolean = False 'by default, user always not exist 
    Dim strFullName As String = "" 

    isValid = IsUserIDExist(userid, strFullName) 
    If isValid Then 
     Return "{'fullname': '" & strFullName & "', 'success': 'true' }" 
    Else 
     Return "{'fullname': '', 'success': 'false' }" 
    End If 

End Function 
+0

什么是数据类型? – ChristopheCVB

+0

请让我看看你的'WebMethod'' AJAX_GetFullName'返回类型有问题。因为如果WebMethod是正确的,alert(data)应该提醒'object Object'。 – naveen

+0

@ChristopheCVB数据类型是字符串 – Alfred

回答

2

试试这个。

$.ajax({ 
    type: "POST", 
    contentType: "application/json;", 
    url: "AJAX_custom_function.aspx/AJAX_GetFullName", 
    data: '{"userid": "' + arguments.Value + '"}', 
    async: false, 
    success: function (data) { 
     try { 
      // convert single quote to double quotes 
      var msg = data.replace(/'/g, "\""); 
      msg = $.parseJSON(msg); 
      alert(msg.fullname); 
     } catch (e) { 
      alert(e.Message); 
     } 
    }, 
    error:function (xhr, status, err){ 
     alert("status=" + xhr.responseText + ", error=" + err); 
    } 

}); 

无需在contentType指定dataTypecharset

+0

它仍然返回undefined。 – Alfred

+0

在两者之间,它返回false为data.hasOwnProperty(“d”) – Alfred

+0

感谢您的帮助。 不知道为什么,我不能把任何的这些功能 $ .parseJSON jQuery.parseJSON JSON.parse 后,我打电话上述任何功能的警报将停止工作。太奇怪了。 我正在使用jquery 1.4.2。有关系吗 ? – Alfred

1

尝试使用:

success: function(data) { 
    if (typeof data == 'string') 
    { 
     data = jQuery.parseJSON(data); 
    } 
    alert(data.fullname); 
} 
+0

JSON.parse +1。 –

+0

运行以下行后:data = JSON.parse(data),警报停止工作已经在使用 – Alfred

+2

@Alfred:所有浏览器都不支持JSON。你可能想添加一个对http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js的引用,因为你使用的是jQuery,所以使用'$ .parseJSON'好多了。 – naveen

0

到字符串JSON对象使用JSON.parse(数据)函数转换成Ajax调用成功功能。我希望这将有所帮助。