The type of data you expect to get back from an Ajax request in jQuery generally requires some instruction. By the method name the data type is specified and in different cases it is provided as part of a configuration object. There are various options:
Text
For transferring simple strings on different pages
Example
$.ajax({
type: "POST",
url:"abc.php",
data: "{}",
async: true,
dataType: "text",
success: function( data ) {
console.log(data);
}
});
Html
For transferring blocks of HTML to be placed on the page.
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
Script
For adding a new script to the page.
$.ajax({ url: 'http://unknown.jquery.com/foo', dataType: 'script', cache: true })
.then(function () { console.log( 'done' ); }, function () { console.log( 'fail' ); });
Json
For transferring JSON-formatted data, which can include strings, arrays, and objects.
$.ajax({
url: "text.php",
type: "POST",
data: {
amount: amount,
firstName: firstName,
lastName: lastName,
email: email
},
dataType: "JSON",
success: function (data) {
console.log("ok");
$("#result").text(data);
}
});
Jsonp
For transferring JSON data from another domain.
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.sites);
},
error: function(e) {
console.log(e.message);
}
});
XML
For transferring data in a custom XML schema.
$.ajax({
url: 'http://theresidency.libsyn.com/rss',
type: 'GET',
dataType: "xml",
success: parseXml
});
});
0 Comment(s)