Reputation: 16639
var module = (function(){
return{
loadJSON: function(url, success, error){
$.when($.ajax({
type: 'GET',
cache: false,
url: url,
contentType: 'application/json',
data: {
format: 'json'
},
success: success,
error: function(err){
console.log('Error: ', err);
}
})).then(function(data){
alert('AJAX completed');
});
}
}
})();
$(document).ready(function(){
function _updateCompany(data){
data = JSON.parse(data);
data = data.data;
for(var i=0; i<data.length; i++){
var item = '<li>Name: ' + data[i]['name'] + ' Total Emp: ' + data[i]['totalCount'] + '</li>';
$('#companyList').append(item);
}
}
function _error(err){
console.log('Error: ', err);
}
module.loadJSON('/path/to/company.json', _updateCompany, _error);
});
Here i get string response and not an object. Hence have to JSON.parse(data);
What is the issue?
Upvotes: 0
Views: 3172
Reputation: 944520
You are getting a plain text response because the server is returning the data with the wrong content-type.
You need the server to include Content-Type: application/json
in the HTTP response header for the JSON data.
If you set dataType: "json"
in the options object you pass to ajax
then you will tell jQuery to ignore the Content-Type and parse it as JSON anyway (but the server is, frankly, misconfigured and you should fix that anyway).
Setting dataType
will also set the Accept
request header to tell the server that JSON is prefered … but that is rather implicit in the URL you are giving it.
Upvotes: 4