开发者

$.parseJSON on $.ajax - problem on parsing response

开发者 https://www.devze.com 2023-02-13 21:26 出处:网络
I don\'t know why, but there is a problem I\'m encountering with $.parseJSON when making an ajax call, I need to check whether the response contains JSON then continue to parse it with $.parseJSON, if

I don't know why, but there is a problem I'm encountering with $.parseJSON when making an ajax call, I need to check whether the response contains JSON then continue to parse it with $.parseJSON, if it does not contain any JSON then it will print out the response in an element (which the response will contain some HTML).

I then tested if eval would do anything, which of course it did, but I don't want to use eval for this.

The code I've got:

$.ajax({ 
    url: 'ajax.php',
    success: function(response)
    {
        var msg = $.parseJSON(response);

            //alert(typeof(response)); <-- returns 'string'

            //alert(typeof(msg)); <-- returns 'object'

            //alert(msg.error); <-- this doesn't work at all.

            //eval(response) <-- returns [object Object]

        if(msg.error !== '')
        {
            ajaxWindow.html(msg.error);
        }
    开发者_开发技巧    else
        {
            ajaxWindow.html(response).hide().slideDown('slow');
        }
    }
});

So how come it's not able to parse the JSON string? jQuery.parseJSON clearly says:

Takes a well-formed JSON string and returns the resulting JavaScript object.

But nothing is being able to be parsed, is this some kind of error, or perhaps a bug?

EDIT: The JSON:

[{"error":"Error loading template"}]


You have an Array, so you need to access it by the first index.

Instead of:

alert( msg.error );

do:

alert( msg[0].error );


Use $.post if possible. It sets the Content-Type to HTML automagicly.

0

精彩评论

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

关注公众号