开发者

json - Jquery return undefined for multiple values in ajax call

I want to return multiple values from Ajax call. So I modified my codes based on this page Jquery return multiple values in ajax call

$.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);
     }    
 });

'alert(data)' returns {"fullname": "Joe", "success" : "true"}

But 'alert(data.fullname)' returns undefined. The correct value should be Joe

Did I missing something? Any advice is very much appreciated.开发者_运维问答

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


Try this.

$.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 );
    }

});

No need to specify dataType and charset in contentType.


Try using :

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


To convert the string to Json object use JSON.parse(data) function with in the success function of Ajax call. i hope this will help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜