5

I am experiencing a strange problem while trying to parse JSON strings in jQuery AJAX response. Here is my code:

$.ajax({
    type: "POST",
    url: "Save",
    data: {
        expiry: expiry,
        settings: settings
    }
}).done(function (msg) {
    alert(msg);
    var obj = jQuery.parseJSON(msg);
    if (obj.status == "done") {
        window.location = obj.redirect;
    }
});

On IE, Chrome, and Safari, I am getting JSON string in alert, but on Firefox, I am getting

[obj XMLDocument]

in the alert.

Here is FF console:

enter image description here

obj is null, but I can see the response JSON string in the console under text attribute

responses=Object { xml=document, text="{"status":"done","redir...ippetImage\/s\/6abb68"}

Any reason for this behavior?

4

2 回答 2

5

问题出在 servlet 方面。我必须设置 contentType 才能使其工作。

response.setContentType("text/JSON");
于 2012-07-09T20:54:51.733 回答
1

这不是一个有效的 JSON 字符串。出于所有意图和目的,JSON 字符串只是 JS 中赋值的右侧。

例如

var x = 7;
        ^
var y = [1,2,3];
        ^^^^^^^
var z = {a:'b', c: 'd'};
        ^^^^^^^^^^^^^^^

如果将 x/y/z 变量转换为 JSON 字符串,由 指示的部分^对应于您将得到的部分。

如果您不能将 json 字符串写为 JS 作业,例如

var x = ...json_string_here...;

那么它不是有效的JSON。您的代码段归结为:

var x = responses=Object { .... }

这是一个语法错误。

于 2012-07-09T20:06:08.643 回答