views:

79

answers:

3

I found this:

Use Python output:

print ‘Content-type: text/x-json\n\n’
print json.dumps([{'title':arr['title']}])

and get json string with Jquery:

$ajax(   
   success: function(msg){
      if(msg[0].title) alert(msg[0].title);
   }
)

It works, who can tell me why it is? Thanks~

+3  A: 

jQuery calls JSON.parse internally on modern browsers that have it if the Content-Type is json

        return window.JSON && window.JSON.parse ?
            window.JSON.parse( data ) :
            (new Function("return " + data))();
meder
thanks for your answer~ medr
Zhaiduo
+1  A: 

I believe jQuery is able to determine the response type based on the header you are sending and automatically evaluate it as JSON.

Chris Gutierrez
+1  A: 

If you set the dataType to "json" or you don't set it and the content-type header contains the string "json", it tries to parse it, you can see the logic at work here:

if ( typeof data === "string" ) {
  // Get the JavaScript object, if JSON is used.
  if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
    data = jQuery.parseJSON( data );

  // If the type is "script", eval it in global context
  } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
    jQuery.globalEval( data );
  }
}

If you're curious, the source for jQuery.parseJSON() is here.

Nick Craver
thanks for your link~ nick
Zhaiduo