为什么jqXHR.responseText返回字符串而不是JSON对象?
我有一个$ .ajax()请求,其dataType设置为“ json”。服务器返回的JSON具有正确的mime类型“ application /
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标头是正确的。
无论如何,只需解析它;这对我有用:
$.ajaxSetup({    "error": function(jqXHR, status, thrownError) {
        alert('error');
        var responseText = jQuery.parseJSON(jqXHR.responseText);
        console.log(responseText);
    }
});
以上是 为什么jqXHR.responseText返回字符串而不是JSON对象? 的全部内容, 来源链接: utcz.com/qa/412798.html







