在 $.ajax 中获取字符串响应

Getting String response in $.ajax

本文关键字:字符串 响应 获取 ajax      更新时间:2023-09-26
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);
});

在这里我得到字符串响应而不是对象。因此必须 JSON.parse(data);

问题出在哪里?

您收到纯文本响应,因为服务器返回的数据内容类型错误。

您需要服务器在 JSON 数据的 HTTP 响应标头中包含Content-Type: application/json


如果你在传递给ajax的选项对象中设置了dataType: "json",那么你将告诉jQuery忽略内容类型并将其解析为JSON(但坦率地说,服务器配置错误,无论如何你都应该修复它)。

设置dataType还将设置Accept请求标头,以告诉服务器首选 JSON ...但这在您提供的 URL 中是相当隐含的。