Example: There is a .js and .php file

The following is written in the .js file:

$.ajax({ url:"index.php", datatype:"json", success:function(result){ console.info(result); } }); 

In the .php file the following

 $array = array("object1" => "Boat","object2" => "Car","object3" => "Ship"); echo json_encode($array); 

PS If in the .js file in the part of the success block, write this: $objectJson = JSON.parse(result) , then the json string will turn into a json object, then the point was for me to specify datatype: "json" ???

  • And what comes to you from the server? Look in the console browser. - Vartlok
  • the string comes, and I need an object, it seems that this is what the datatype should do: "json" - MaximPro
  • Add it to the question, please. - Vartlok
  • added correctly? - MaximPro

2 answers 2

 dataType:"json" 

T - c capital letters.

  • Exactly, I also thought about it, but did not pay special attention to it, then such a counter question, why do we need this function JSON.parse () ;? - MaximPro
  • @MaximPro, Personally, I don’t see any difference between them, except in the version with JSON.parse (); we can test the result for anything before parsing. - koks_rs
  • @MaximPro Consider that in JavaScript the case of fields and variables matters. JSON.parse() needed to convert a JSON string to an object. It is this function that jQuery calls when it receives JSON via AJAX with the appropriate Content-Type or when you force a dataType: 'json' - tutankhamun
  • @tutankhamun I know that the JSON.parse () function converts from string to object just like the dataType: "json", but why so many variations? where is the meaning? - MaximPro
  • @MaximPro When you force a dataType:"json" jQuery tries to convert the response to an object using the JSON.parse() function even if a JSON string comes with the Content-Type: text/html - tutankhamun

The server response should come with the correct Content-Type header.

That is, perhaps you should only add:

 header('Content-Type: text/javascript'); 

Or more correctly (as per RFC 4627 ):

 header('Content-Type: application/json');