简体   繁体   中英

Getting String response in $.ajax

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM