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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5825465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:50:17  来源:igfitidea点击:

Why is jqXHR.responseText returning a string instead of a JSON object?

ajaxjsonjquery-1.5jqxhr

提问by Tjorriemorrie

I have an $.ajax() request with the dataType set to "json." The server is returning JSON with the correct mime type of "application/json." And yet the responseText in my jqXHR object is always a string. What am I doing wrong? Is this how it's supposed to work?

我有一个 $.ajax() 请求,其中 dataType 设置为“json”。服务器正在返回具有正确 mime 类型“application/json”的 JSON。然而,我的 jqXHR 对象中的 responseText 始终是一个字符串。我究竟做错了什么?这是它应该如何工作?

Here's how I'm making the call:

这是我拨打电话的方式:

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

So I have have to do a $.parseJSON(jqXHRObject.responseText)to get an actual object. This seems unnecessary as $.ajax() should be automatically converting responseText according to the docs. Thanks!

所以我必须做一个$.parseJSON(jqXHRObject.responseText)才能得到一个实际的对象。这似乎没有必要,因为 $.ajax() 应该根据文档自动转换 responseText 。谢谢!

回答by Tjorriemorrie

I had the same problem. I returns a string because it formulated from an exception. E.g. I use a kernel listener with serialization to json on my Symfony2 project. Which is correct for proper REST headers.

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

Anyway, just parse it; this works for me:

无论如何,只需解析它;这对我有用:

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

回答by chridam

Try

尝试

$.ajaxSetup({
    "error": function(jqXHR, status, thrownError) {
        alert('error');            
        console.log(jqXHR.responseJSON);
    }
});

回答by kcbanner

You are using $.ajax in a way the docs don't describe. Using jsonas the dataType just means that the data passed to the successcallback will be parsed. Use it like this:

您正在以文档未描述的方式使用 $.ajax。使用json的具体的数据类型只是意味着传递给数据success的回调将被解析。像这样使用它:

$.ajax({
  dataType:'json',
  type: 'GET',
  url: "http://example.com/api/"
  success: function(data, textStatus, jqXHR) {
    // `data` contains parsed JSON
  },
  error: function(jqXHR, textStatus, errorThrown) {
     // Handle any errors
  }
});

回答by michaeltomer

I don't see anything in the documentation that suggests responseText would be anything other than exactly what the name implies: text.

我在文档中没有看到任何内容表明 responseText 可能不同于名称所暗示的内容:text。

Why not just use .getJSON? That would get rid of half of the code you wrote, and it'll convert the response to JSON. Win/win.

为什么不直接使用.getJSON?这将删除您编写的一半代码,并将响应转换为 JSON。赢/赢。

回答by Aravindh Gopi

Step 1: Stringify the jqXHR

第 1 步:将 jqXHR 字符串化

var errorString = JSON.stringify(jqXHR.responseText);

Step 2: change that string to Jquery Object

第 2 步:将该字符串更改为 Jquery 对象

var $errorObj = $(errorString);

Step 3: Find and get what part of responseText you want.

第 3 步:查找并获取您想要的 responseText 部分。

var errorMessage = $errorObj.find('p').eq(1).text(); 

/* Here Im finding `Message:` thrown by the server, which is inside <p> tag */

Thats it.

就是这样。

$.ajax( /* ... */ ).fail( function(jqXHR, textStatus, errorThrown) {

     var errorString = JSON.stringify(jqXHR.responseText);
     var $errorObj = $(errorString);
     var errorMessage = $errorObj.find('p').eq(1).text();

     alert(errorMessage);

    } );