Understanding $.ajax converters
in Using jQuery
•
6 years ago
Hi,
I'm not sure if I understood well what converters actually do. Here's an explanation from http://api.jquery.com/jquery.ajax/ :
Concretely:
I'm not sure if I understood well what converters actually do. Here's an explanation from http://api.jquery.com/jquery.ajax/ :
converters (default:{"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}
)Type: PlainObjectAn object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5)
Concretely:
-
converters: {
"text json": function(data) {
return data;
}
}
without this, one application from one tutorial does not work... here's the rest of the code:
-
$("#buttonDiv").click(function(e) {
var unetiPodaci = $("#orderForm").serialize();
e.preventDefault();
$.ajax({
url: "http://localhost",
type: "post",
data: unetiPodaci,
dataType: "json",
dataFilter: function(siroviOdgovor, dataType) {
var jsonOdgovor = $.parseJSON(siroviOdgovor);
var cleanData = {
totalItems: jsonOdgovor.totalItems,
totalPrice: jsonOdgovor.totalPrice
};
delete jsonOdgovor.totalItems;
delete jsonOdgovor.totalPrice;
cleanData.products = [];
for (prop in jsonOdgovor) {
cleanData.products.push({
name: prop,
quantity: jsonOdgovor[prop]
})
}
return cleanData;
},
converters: {
"text json": function(data) {
return data;
}
},
success: function(data) {
obradiPrimljeniOdgovor(data);
}
})
})
Correct me if I'm wrong , maybe it means that the response (which is a text) will be converted to json? If so, then why is something like that needed when we have:
- dataType:
"json",
dataFilter: function(siroviOdgovor, dataType) {
var jsonOdgovor = $.parseJSON(siroviOdgovor);
where it is already
stated that we
expect "json" and in dataFilter we parsed response to JSON?
1