36 ajax json jqxhr jquery-1.5
我有一个$ .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
Run Code Online (Sandbox Code Playgroud)
所以我必须做一个$.parseJSON(jqXHRObject.responseText)
获得一个实际的对象.这似乎是不必要的,因为$ .ajax()应该根据文档自动转换responseText.谢谢!
Tjo*_*rie 51
我有同样的问题.我返回一个字符串,因为它是根据异常制定的.例如,我在我的Symfony2项目中使用带有序列化的内核侦听器到json.这对于正确的REST标头是正确的.
无论如何,只需解析它; 这对我有用:
$.ajaxSetup({
"error": function(jqXHR, status, thrownError) {
alert('error');
var responseText = jQuery.parseJSON(jqXHR.responseText);
console.log(responseText);
}
});
Run Code Online (Sandbox Code Playgroud)
chr*_*dam 23
尝试
$.ajaxSetup({
"error": function(jqXHR, status, thrownError) {
alert('error');
console.log(jqXHR.responseJSON);
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
82218 次 |
最近记录: |