gpt4 book ai didi

ajax - 为什么 jqXHR.responseText 返回字符串而不是 JSON 对象?

转载 作者:IT老高 更新时间:2023-10-28 12:48:06 26 4
gpt4 key购买 nike

我有一个数据类型设置为“json”的 $.ajax() 请求。服务器正在返回带有正确 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。谢谢!

最佳答案

我遇到了同样的问题。我返回一个字符串,因为它是根据异常制定的。例如。我在 Symfony2 项目中使用带有序列化到 json 的内核监听器。这对于正确的 REST header 是正确的。

不管怎样,只要解析它;这对我有用:

$.ajaxSetup({
"error": function(jqXHR, status, thrownError) {
alert('error');
var responseText = jQuery.parseJSON(jqXHR.responseText);
console.log(responseText);
}
});

关于ajax - 为什么 jqXHR.responseText 返回字符串而不是 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5825465/

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