而不是一个JSON对象

而不是一个JSON对象

本文介绍了为什么jqXHR.responseText返回一个字符串,而不是一个JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有与数据类型设置为$阿贾克斯()请求JSON。服务器返回JSON与正确的MIME类型为application / json的。然而在我jqXHR对象的responseText的始终是一个字符串。我究竟做错了什么?请问这是怎么它应该工作?

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?

下面就是我正在做的电话:

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

所以我必须做一个 $。parseJSON(jqXHRObject.responseText)来获得一个实际的对象。这似乎是不必要的,因为$。阿贾克斯()应该会自动根据文档转换responseText的。谢谢!

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!

推荐答案

我有同样的问题。我返回一个字符串,因为它从一个例外规定。例如。我用一个内核侦听器序列化到JSON我的Symfony2的项目。这是正确的适当休息头。

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.

总之,只要对其进行分析;这对我的作品:

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);
    }
});

这篇关于为什么jqXHR.responseText返回一个字符串,而不是一个JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:59