What is the difference between Ajax's dataTypes in jQuery?

7

I'm learning jQuery and need to know the difference between Ajax's dateTypes.

dataType: "xml"

      dataType: "json"

            dataType: "script"

                   dataType: "html"

How does this influence script execution and result return?

    
asked by anonymous 29.07.2015 / 20:01

2 answers

7
  

Source: link

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 call 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: Loads 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
              }
});
    
29.07.2015 / 21:59
2

@JeffersonSilva's response is quite descriptive, but I'd like to present a more technical answer.

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

So, the script dataType refers to application/javascript .

Following the logic, it would look something like this:

dataType  MIME type
--------  ----------
xml       text/xml ou application/xml
json      application/json
script    application/javascript
html      text/html
    
30.07.2015 / 06:16