1

In my javascript, I have a jQuery ajax get request:

    $.get(uri, callback_function, 'json');  

In firebug, I can see the response header:

 Content-Type   application/json 

the response content:

{ "status": true, "data": "my test output" }    

There is even a JSON tab in Net -> XHR which shows the returned data pretty-printed.

However, why in my callback function do I need to parse the data I get?

function callback_function(data) {
    console.log(data); // { "status": true, "data": "my test output" } 
                                    //  (printed in black)
    console.log(data.status); // undefined
    var parsedData = JSON.parse(data);   // why is this needed?? 
    console.log(parsedData); //  Object { status=true, data="my test output"} 
                                                //  (printed in colours)
    console.log(parsedData.status); // true
}

From the documentation:
https://api.jquery.com/jQuery.get/
jQuery.get( url [, data ] [, success ] [, dataType ] )
dataType Type: String The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).

Since I am both expecting and getting a JSON object (see HTTP response header), why do I need to parse what appears to be a mere string?

augustin
  • 14,373
  • 13
  • 66
  • 79
  • 2
    Good question. jQuery should do this automatically for you. To be clear: JSON needs to be parsed since it is just text, but with the right content type, jQuery does that automatically. – Felix Kling Sep 02 '16 at 04:20
  • 1
    Its batter to use $.ajax method with dataType: json – Harsh Sanghani Sep 02 '16 at 04:22
  • I am stuck with an older version of jQuery, so it might be a bug in the library. But I tried as Harsh Sanghani suggested, and I don't encounter this bug (?) using $.ajax(). Thanks. – augustin Sep 02 '16 at 05:00

1 Answers1

0

At the moment it is just a string, basically, since you then need to parse it to convert it into a javascript object.

You can see it in the debugger pretty formatted as I expect the debugger is also parsing it for you, since showing a long string would be less useful.

So, you parse so you can use the result you get in the language that you need, in this case, in javascript.

James Black
  • 41,583
  • 10
  • 86
  • 166