仅在Firefox中出现JSON语法错误 [英] JSON syntax error in firefox only
问题描述
使用$.parseJSON()
时,我在FireFox中遇到语法错误.相同的代码可在Chrome/Chromium和Safari上正常工作.
Im getting a syntax error in FireFox when using $.parseJSON()
. The same code works properly on Chrome/Chromium, and Safari.
我调用此函数以获取随机生成的令牌进行设置.
I call this function to get a random generated token to set.
function getToken() {
var url = "/csrf_token_generate";
$.ajax({
url: url,
method: "GET"
}).done(function(data) {
console.log(data); // Logs the data from the call
var json = $.parseJSON(data); // Where the error occurs
token = json.token;
console.log(token);
});
}
URL /csrf_token_genrate
返回类似于{"token":"$2y$10$jcr.P3FNqeji6RqD93LnxeIKs9gYNiPj7cboahz8RCCSgKw7VOfhi"}
The URL /csrf_token_genrate
returns a JSON object similar to {"token":"$2y$10$jcr.P3FNqeji6RqD93LnxeIKs9gYNiPj7cboahz8RCCSgKw7VOfhi"}
在URL中,我将Content-Type
设置为application/json
,这在其他所有浏览器中都可以使用.
In the URL, I am setting the Content-Type
to application/json
which works in every other browser.
我得到的错误是这个
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
n.parseJSON() jquery.min.js:4
getToken/<() wheel.bak.js:94
n.Callbacks/j() jquery.min.js:2
n.Callbacks/k.fireWith() jquery.min.js:2
x() jquery.min.js:4
.send/b/<() jquery.min.js:4
正在被console.log()
编辑的对象是这个Object { token: "$2y$10$60vxSZiVqushBLVHSR5jPO6MquD4…" }
The object that is being console.log()
'ed is this Object { token: "$2y$10$60vxSZiVqushBLVHSR5jPO6MquD4…" }
我似乎无法追查为什么它仅在FireFox中不起作用,而在其他浏览器中却可以正常工作.
I just can't seem to track down why it won't work in only FireFox, but works fine in other browsers.
更新1
我发现firefox试图解析一个已经解析的对象,所以我更改了代码,使其保持不变
I figured out that firefox was trying to parse an already parsed object, so I changed the code to be along this
function getToken() {
var url = "/csrf_token_generate";
$.ajax({
url: url,
method: "GET"
}).done(function(data) {
var json = data;
token = json.token;
console.log(token);
});
}
现在可以在Firefox中使用,但不能在Chromium中使用.
Which now works in firefox, but not Chromium.
那该做什么呢?
推荐答案
我认为您应该检查Response Headers
-> Content-Type
以找到实际的Data Type
.
兼容的代码应该像这样.
I think you should check the Response Headers
-> Content-Type
to find the actual Data Type
.
And the compatible code should like this.
# for chrome
if(typeof data === 'string') {
}
#for firefox
if(typeof data === 'object') {
}
这篇关于仅在Firefox中出现JSON语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!