What is the difference between Ajax dataTypes in jQuery?

Asked

Viewed 16,374 times

9

I am learning jQuery and I need to know the difference between Ajax dateTypes.

dataType: "xml"

      dataType: "json"

            dataType: "script"

                   dataType: "html"

How this influences the execution of the script and return of the result?

  • The answers below are decent, but no one answered: ... How this influences the execution of the script and return of the result ...

2 answers

13

Source: http://api.jquery.com/jquery.ajax/

XML: Returns an xml document that can be processed via Jquery. the return must be treated as XML nodes

$.ajax({
 url : "xml.xml",
 dataType : "xml",
 success : function(xml){
        $(xml).find('item').each(function(){
            var titulo = $(this).find('title').text();
            console.log(titulo);
        });
    }
});

JSON: Evaluates the response as JSON and returns a javascript object

$.ajax({
    url : "json.php",
    dataType : "json",
    success : function(data){
                 for($i=0; $i < data.length; $i++)
                   console.log(data[$i])
              }
});

JSONP: Request very similar to JSON, except that it is possible to make calls through different domains, with an additional parameter called callback.

//json.php
{ foo: 'bar' }

--

//jsonp.php
meucallback({ foo: 'bar' })

--

$.ajax({
    url : "www.outrosite.com/jsonp.php",
    dataType : "jsonp",
    jsonpCallback : "meucallback"
});

--

function meucallback(obj)
{
    console.log(obj);
}

SCRIPT: Load an external script in string format

//externo.js
alert("OLA")

--

$.ajax({
    url : "externo.js",
    dataType : "script",
    success : function(scriptString){
               eval(scriptString); //executa o script retornado
              }
});

6

The reply of @Jeffersonsilva is quite skeptical, but I would like to present a more technical answer.

jQuery dataTypes are based on MIME Types. These are used in the HTTP header, where it refers to Content-Type.

Thus, the script dataType refers to application/javascript.

Following the logic, it would be something like this:

dataType  MIME type
--------  ----------
xml       text/xml ou application/xml
json      application/json
script    application/javascript
html      text/html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.