简体   繁体   中英

jQuery.parseJSON not working unless copied in a different string variable

I am fairly new to javascript and jQuery. I m pretty sure there is something simple that i am missing here. The code below will output :

[{
    "cli_surname":"\u0392\u03bf\u03bd\u03b1\u03c0\u03ac\u03c1\u03c4\u03b7\u03c2",
    "cli_name":"\u039d\u03b1\u03c0\u03bf\u03bb\u03ad\u03c9\u03bd",
    "cli_sex":"M",
    "cli_dob":"1769-08-15",
    "cli_insurance":"1",
    "cli_phone":"9999999999",
    "cli_mobile":"9999999999",
    "cli_email":"bonaparte@hotmail.com",
    "cli_address":"\u0392\u03b1\u03c4\u03b5\u03c1\u03bb\u03ce 18",
    "ct_name":"\u0391\u03b3\u03af\u03b1 \u0392\u03b1\u03c1\u03b2\u03ac\u03c1\u03b1",
    "cli_comments":"\u039c\u03ad\u03b3\u03b1\u03c2"
}]

to $("#userInfo") as instructed but jQuery.parseJSON will fail.

$.ajax({        
    url: url,
    type: "POST",
    data: "c=" + selected.val(),
    success: function (json) {
        $("#userInfo").html(' ' + json);

        var obj = jQuery.parseJSON( json );
        alert( obj[0].cli_name );
    },
    error: function (xhr) {
        $("#userInfo").html('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
    }
}); 

Now if i copy the output of the above code from $("#userInfo") and paste it in a new variable called 'data' and parse that, it works.

$.ajax({        
    url: url,
    type: "POST",
    data: "c=" + selected.val(),
    success: function (json) {
        $("#userInfo").html(' ' + json);

        data = '[{"cli_surname":"\u0392\u03bf\u03bd\u03b1\u03c0\u03ac\u03c1\u03c4\u03b7\u03c2","cli_name":"\u039d\u03b1\u03c0\u03bf\u03bb\u03ad\u03c9\u03bd","cli_sex":"M","cli_dob":"1769-08-15","cli_insurance":"1","cli_phone":"9999999999","cli_mobile":"9999999999","cli_email":"bonaparte@hotmail.com","cli_address":"\u0392\u03b1\u03c4\u03b5\u03c1\u03bb\u03ce 18","ct_name":"\u0391\u03b3\u03af\u03b1 \u0392\u03b1\u03c1\u03b2\u03ac\u03c1\u03b1","cli_comments":"\u039c\u03ad\u03b3\u03b1\u03c2"}]';
        var obj = jQuery.parseJSON( data );
        $("#userInfo").html(" " + data);
        alert( obj[0].cli_name );
    },
    error: function (xhr) {
        $("#userInfo").html('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
    }
});

When applying typeof to both variables, the result is string . What gives? How is it that i can parse the data variable and not the json variable since they are both strings and appear to contain the same data?

The Ajax call will do the parsing for you internally.

So, your parameter json to your success function already contains a valid javascript object and that's why the parsing fails: its an object but not a string.

The construct $("#userInfo").html(' ' + json); then will convert the json to a string again and that's why you see proper content in the div.

change:

$.ajax({        
    url: url,
    type: "POST",
    dataType: 'json', // this will force the response to be Json 
                      // even if MIME-Type tells something different!
    data: "c=" + selected.val(),
    success: function (json) {
        $("#userInfo").html(' ' + json);

        // unnecessary var obj = jQuery.parseJSON( json );
        alert( json[0].cli_name );
    },
    error: function (xhr) {
        $("#userInfo").html('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
    }
}); 

Just added dataType in order to locally overwrite erroneous MIME-Type headers of the response. According to the first answer to this Q

Try this:
Response will be parse to json automatically

          $.ajax({
                url: url,
                type: "POST",
                data: "c=" + selected.val(),
                dataType: 'json',     // this param talk that response will be parse automatically
                success: function(data) {
                    console.log(data)
                }
            });

The reason why your json variable is not parsed while ur data variable is being parsed is because your json variable has the new line characters (\\n).

Since your data variable has the string in one line, that is, no new line characters, the function parses the string successfully.

I should probably also point out that characters such as tab (\\t) or any other escape character in the string provided to the JSON parsing function will cause the function to fail.

Bad string var for parsing:

var myVar = "This is a text"; //will fail due to new line characters.
var myVar = 'My Friend\'s birthday'; //will fail due to the "\" before "'"
var myVar = '   This is a text.' //will fail due to the tab character at the beginning of the line

"The JSON standard does not permit "control characters" such as a tab or newline." - http://api.jquery.com/jquery.parsejson/

Check the link above for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM