我使用 $.ajax() 发起请求,dataType 设置为 "json"。服务器返回正确的 mime 类型为 "application/json" 的 JSON 数据。但是 jqXHR 对象中的 responseText 总是一个字符串。我做错了什么?这样是正常工作的吗?
以下是我的请求调用方式:
var options = {
dataType:'json',
type: 'GET',
url: "http://example.com/api/"
};
var key = "PassToCallback";
var jqXHRObject = $.ajax(options).then(
function(data, textStatus, jqXHR, key) {
this.success(data, textStatus, jqXHR, key);
},
function(jqXHR, textStatus, errorThrown) {
this.error(jqXHR, textStatus, errorThrown);
}
);
console.log(jqXHRObject.getResponseHeader("content-type")); // application/json
console.log(typeof jqXHRObject.responseText); // string
所以我必须执行$.parseJSON(jqXHRObject.responseText)
才能获得一个实际的对象。根据文档,这似乎是不必要的,因为$.ajax()应该自动将responseText转换。谢谢!