简体   繁体   中英

Why JSON.parse is not working?

I set the dataType to 'text' because I don't want to Jquery parse my JSON automatically. My code is the following:

var membId = '5';
$('#submitNewDescription').live('click',function(){
    //An ajax request is made to update the DB
    $.ajax({
        url: '../../cgi-bin/qualification.py',
        type: 'POST',
        data: ({newDescription:$('#newDescription').val(),id:membId}),
        dataType: 'text',
        cache: 'false',
        success: function(data){
            json = JSON.parse(data);
            console.log(data);
            console.log(json);
        }
    });
});

And it returns that string: {"error":["ORA-01031 insufficient privileges"]} in both console.log commands. It means that the parse isn't working since it doesn't return a JavaScript object. JSONLint says to me that is a valid JSON.

Anyone has an idea of what is happening?

Thanks

EDIT

I can set to 'json', it is not problem. The problem is that JSON.parse and $.parseJSON should work. Since they are not, I changed 'dataType' to 'json', but the same string is returned. I have no idea what is happening.

Probably because you're looking for $.parseJSON instead? Also I beieve jQuery will look at the data and make a best-guess at parsing it before passing it off to the callback. So, if it looks like JSON chances are jQuery's already giving you a JavaScript object back which then can't be re-parsed using JSON.parse / $.parseJSON .

You can also change your dataType field to 'json' and let jQuery do it for you...

dataType: 'text'更改为dataType: "json"以及JSON.parse更改$.parseJSON

The JSON library doesn't exist in all browsers. You might need to include your own like http://developer.yahoo.com/yui/json/

Or like the others suggested, use the jQuery one. You might also want to declare json like var json = ...

In my case, I got it to work as follows:

  • from the server (a servlet), I specified json as the data type of the response
  • the jquery call then already parses the response param into a JSON object (so I didn't need to run $.parseJSON) ... thank you https://stackoverflow.com/a/6465506/2162226 !

Notice I can: access the json field directly in the response object

$.ajax({
        type: "POST",
        url: baseUrl,
        dataType: "json",
        data: theData,
        success: function(response) {

                alert(' status = ' + response.status);
                processResponseJSON(response);
        },

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