gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:11:55 25 4
gpt4 key购买 nike

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 响应 header 中包含 Content-Type: application/json

<小时/>

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

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

关于javascript - 在 $.ajax 中获取字符串响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36038828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com