Javascript 未捕获的语法错误:意外标记:
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3143698/
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
Uncaught SyntaxError: Unexpected token :
提问by trobrock
I am running an AJAX call in my MooTools script, this works fine in Firefox but in Chrome I am getting a Uncaught SyntaxError: Unexpected token :error, I cannot determine why. Commenting out code to determine where the bad code is yields nothing, I am thinking it may be a problem with the JSON being returned. Checking in the console I see the JSON returned is this:
我在我的 MooTools 脚本中运行 AJAX 调用,这在 Firefox 中工作正常,但在 Chrome 中我收到Uncaught SyntaxError: Unexpected token :错误,我无法确定原因。注释掉代码以确定错误代码的位置不会产生任何结果,我认为这可能是返回 JSON 的问题。在控制台中检查我看到返回的 JSON 是这样的:
{"votes":47,"totalvotes":90}
I don't see any problems with it, why would this error occur?
我没有看到它有任何问题,为什么会发生这个错误?
vote.each(function(e){
e.set('send', {
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = JSON.decode(resp);
if (!j) return false;
var restaurant = e.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
});
e.addEvent('submit', function(e){
e.stop();
this.send();
});
});
采纳答案by trobrock
I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:
我刚刚解决了这个问题。标准请求调用出现问题,所以这是我使用的代码:
vote.each(function(element){
element.addEvent('submit', function(e){
e.stop();
new Request.JSON({
url : e.target.action,
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = resp;
if (!j) return false;
var restaurant = element.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
}).send(this);
});
});
If anyone knows why the standard Request object was giving me problems I would love to know.
如果有人知道为什么标准 Request 对象给我带来了问题,我很想知道。
回答by andy magoon
Seeing red errors
看到红色错误
Uncaught SyntaxError: Unexpected token <
未捕获的语法错误:意外的标记 <
in your Chrome developer's console tab is an indication of HTML in the response body.
在 Chrome 开发人员的控制台选项卡中,响应正文中的 HTML 指示。
What you're actually seeing is your browser's reaction to the unexpected top line <!DOCTYPE html>from the server.
您实际看到的是浏览器对<!DOCTYPE html>来自服务器的意外顶线的反应。
回答by Edward Abrams
Just an FYI for people who might have the same problem -- I just had to make my server send back the JSON as application/json and the default jQuery handler worked fine.
对于可能有同样问题的人,仅供参考——我只需要让我的服务器将 JSON 作为 application/json 发回,并且默认的 jQuery 处理程序工作正常。
回答by Grim...
This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=?to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"}and getting the error.
这只是发生在我身上,原因不是上述原因。我正在使用 jQuery 命令 getJSON 并添加callback=?使用 JSONP(因为我需要跨域),并返回 JSON 代码{"foo":"bar"}并获取错误。
This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})
这是因为我应该包含回调数据,例如 jQuery17209314005577471107_1335958194322({"foo":"bar"})
Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:
这是我用来实现这一点的 PHP 代码,如果使用 JSON(没有回调),它会降级:
$ret['foo'] = "bar";
finish();
function finish() {
header("content-type:application/json");
if ($_GET['callback']) {
print $_GET['callback']."(";
}
print json_encode($GLOBALS['ret']);
if ($_GET['callback']) {
print ")";
}
exit;
}
Hopefully that will help someone in the future.
希望这会在将来对某人有所帮助。
回答by Keven
I thought I'd add my issue and resolution to the list.
我想我会将我的问题和解决方案添加到列表中。
I was getting: Uncaught SyntaxError: Unexpected token <and the error was pointing to this line in my ajax success statement:
我得到:Uncaught SyntaxError: Unexpected token <并且错误指向我的 ajax 成功语句中的这一行:
var total = $.parseJSON(response);
I later found that in addition to the json results, there was HTML being sent with the response because I had an error in my PHP. When you get an error in PHP you can set it to warn you with huge orange tables and those tables were what was throwing off the JSON.
后来发现除了json结果,还有HTML和响应一起发送,因为我的PHP有错误。当您在 PHP 中遇到错误时,您可以将其设置为使用巨大的橙色表警告您,而这些表是丢弃 JSON 的原因。
I found that out by just doing a console.log(response)in order to see what was actually being sent. If it's an issue with the JSON data, just try to see if you can do a console.log or some other statement that will allow you to see what is sent and what is received.
我只是通过执行 aconsole.log(response)来查看实际发送的内容来发现这一点。如果是 JSON 数据的问题,请尝试查看是否可以执行 console.log 或其他一些语句,以查看发送的内容和接收的内容。
回答by Micha? Per?akowski
When you request your JSON file, server returns JavaScript Content-Typeheader (text/javascript) instead of JSON (application/json).
当您请求 JSON 文件时,服务器返回 JavaScriptContent-Type标头 ( text/javascript) 而不是 JSON ( application/json)。
According to MooTools docs:
根据MooTools 文档:
Responses with javascript content-type will be evaluated automatically.
带有 javascript content-type 的响应将被自动评估。
In result MooTools tries to evaluate your JSON as JavaScript, and when you try to evaluate such JSON:
结果 MooTools 尝试将您的 JSON 评估为 JavaScript,当您尝试评估此类 JSON 时:
{"votes":47,"totalvotes":90}
as JavaScript, parser treats {and }as a block scope instead of object notation. It is the same as evaluating following "code":
作为 JavaScript,解析器将{和}视为块范围而不是对象表示法。它与评估以下“代码”相同:
"votes":47,"totalvotes":90
As you can see, :is totally unexpected there.
如您所见,:那里完全出乎意料。
The solution is to set correct Content-Typeheader for the JSON file. If you save it with .jsonextension, your server should do it by itself.
解决方案是Content-Type为 JSON 文件设置正确的标头。如果你用.json扩展名保存它,你的服务器应该自己做。
回答by Zectbumo
It sounds like your response is being evaluated somehow. This gives the same error in Chrome:
听起来您的回答正在以某种方式进行评估。这在 Chrome 中给出了相同的错误:
var resp = '{"votes":47,"totalvotes":90}';
eval(resp);
This is due to the braces '{...}' being interpreted by javascript as a code block and not an object literal as one might expect.
这是因为大括号 '{...}' 被 javascript 解释为一个代码块,而不是人们可能期望的对象字面量。
I would look at the JSON.decode() function and see if there is an eval in there.
我会查看 JSON.decode() 函数,看看那里是否有 eval。
Similar issue here: Eval() = Unexpected token : error
这里有类似的问题: Eval() = Unexpected token : error
回答by Hammad Khan
If nothing makes sense, this error can also be caused by PHP Error that is embedded inside html/javascript, such as the one below
如果没有任何意义,此错误也可能是由嵌入在 html/javascript 中的 PHP Error 引起的,如下所示
<br />
<b>Deprecated</b>: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in <b>C:\Projects\rwp\demo\en\super\ge.php</b> on line <b>54</b><br />
var zNodes =[{ id:1, pId:0, name:"ACE", url: "/ace1.php", target:"_self", open:true}
Not the <br />etc in the code that are inserted into html by PHP is causing the error. To fix this kind of error (suppress warning), used this code in the start
不是<br />由 PHP 插入到 html 的代码中的etc 导致错误。要修复此类错误(抑制警告),请在开始时使用此代码
error_reporting(E_ERROR | E_PARSE);
To view, right click on page, "view source" and then examine complete html to spot this error.
要查看,请右键单击页面,“查看源代码”,然后检查完整的 html 以发现此错误。
回答by Jerinaw
This happened to because I have a rule setup in my express server to route any 404 back to /#plus whatever the original request was. Allowing the angular router/js to handle the request. If there's no js route to handle that path, a request to /#/whateveris made to the server, which is just a request for /, the entire webpage.
发生这种情况是因为我在我的快速服务器中设置了一个规则来将任何 404 路由回/#以及原始请求的任何内容。允许角度路由器/js 处理请求。如果没有 js 路由来处理该路径,/#/whatever则会向服务器发出请求,这只是/对整个网页的请求。
So for example if I wanted to make a request for /correct/somejsfile.jsbut I miss typed it to /wrong/somejsfile.jsthe request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get
因此,例如,如果我想向服务器发出请求,/correct/somejsfile.js但我错过了将其输入/wrong/somejsfile.js到服务器的请求。该位置/文件不存在,因此服务器以302 location: /#/wrong/somejsfile.js. 浏览器愉快地跟随重定向并返回整个网页。浏览器将页面解析为js,你得到
Uncaught SyntaxError: Unexpected token <
未捕获的语法错误:意外的标记 <
So to help find the offending path/request look for 302 requests.
因此,为了帮助找到有问题的路径/请求,请查找 302 请求。
Hope that helps someone.
希望能帮助某人。
回答by Serip88
"Uncaught SyntaxError: Unexpected token" error appearance when your data return wrong json format, in some case, you don't know you got wrong json format.
please check it with alert(); function
“ Uncaught SyntaxError: Unexpected token” 当你的数据返回错误的json格式时出现错误,在某些情况下,你不知道你得到了错误的json格式。
请使用 alert() 进行检查;功能
onSuccess : function(resp){
alert(resp);
}
your message received should be: {"firstName":"John", "lastName":"Doe"}
and then you can use code below
您收到的消息应该是:{"firstName":"John", "lastName":"Doe"}
然后您可以使用下面的代码
onSuccess : function(resp){
var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp);
}
with out error "Uncaught SyntaxError: Unexpected token"
but if you get wrong json format
ex:
没有错误“ Uncaught SyntaxError: Unexpected token”
但如果你得到错误的json格式
例如:
...{"firstName":"John", "lastName":"Doe"}
...{"firstName":"John", "lastName":"Doe"}
or
或者
Undefined variable: errCapt in .... on line<b>65</b><br/>{"firstName":"John", "lastName":"Doe"}
so that you got wrong json format, please fix it before you JSON.decode or JSON.parse
所以你得到了错误的 json 格式,请在 JSON.decode 或 JSON.parse 之前修复它

