user2520410
user2520410

Reputation: 479

AJAX call in jQuery, what defines a "json" as parameter?

I found this line of code. This AJAX call's last parameter is a string, "json".

What does it stand for?

$.get(theUrl, function(e) {
    make(e);
  }, "json")

Upvotes: 0

Views: 63

Answers (4)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

This parameter indicates the expected return type. The possible values are xml, json, script, or html. When you specify the expected return type, jQUery will automatically parse the response form the server and provide to the success callback an already processed variable.

If you omit this parameter then jQuery will use the Content-Type response header that is sent from the server to determine how to process the response. For example if the server sends Content-Type: application/json then jQuery will automatically parse the response into a javascript object that will be passed to the success callback.

Usually if the server side script that you are calling is properly written and respects web standards by specifying the correct Content-Type response header you don't need to be explicitly setting this parameter in your AJAX call:

$.get(theUrl, function(e) {
    // If the server set the Content-Type header to application/json
    // then the "e" variable passed to this function will already be
    // a parsed javascript object
    make(e);
});

Upvotes: 1

melvas
melvas

Reputation: 2356

it's a returned data type: see the last paragraph

Upvotes: 0

Petar Vasilev
Petar Vasilev

Reputation: 4735

That's any data you want to be passed to the server which needs to be in object notation like so:

{
   param1: "data1",
   param2: "data2"
}

these will basically become the get parameters at the end of the request url like so:

http://example-site.com/request-link?param1=data1&param2=data2

Upvotes: 0

It means that ajax will return data type json

dataType: (example: xml, json, script, or html)

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback).


"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)

Upvotes: 4

Related Questions