Uncaught SyntaxError: Unexpected token :
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:
{"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();
});
});
Seeing red errors
Uncaught SyntaxError: Unexpected token <
in your Chrome developer's console tab is an indication of HTML in the response body.
What you're actually seeing is your browser's reaction to the unexpected top line <!DOCTYPE html> from the server.
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.
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.
This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})
Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:
$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.
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.
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:
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.
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.
파일을 는 JavaScript JSON을 합니다.Content-Typeheader)text/javascriptJSON)이 ( application/json를 참조해 주세요.
MuTools 문서에 따르면:
javascript content-type 응답은 자동으로 평가됩니다.
그 결과 MooTools는 JSON을 JavaScript로 평가하려고 합니다.또, 이러한 JSON을 평가하려고 하면, 다음과 같이 됩니다.
{"votes":47,"totalvotes":90}
는 JavaScript를 합니다.{ ★★★★★★★★★★★★★★★★★」}객체 표기 대신 블록 스코프로 지정합니다.이것은, 다음의 「코드」를 평가하는 것과 같습니다.
"votes":47,"totalvotes":90
바와 같이, '우리'는 '우리'입니다.:전혀 예상치 못한 일이었습니다.
은 올바른 설정을 입니다.Content-TypeJSON の j j j j 。「」와 함께 .json이치노
당신의 대응이 어떻게든 평가되고 있는 것 같습니다.이로 인해 Chrome에서도 동일한 오류가 발생합니다.
var resp = '{"votes":47,"totalvotes":90}';
eval(resp);
교정기 '{...}'은 javascript에 의해 코드 블록으로 해석되며 예상대로 객체 리터럴이 아닙니다.
JSON.decode() 함수를 보고 평가가 있는지 확인합니다.
유사한 문제: Eval() = 예기치 않은 토큰: 오류
오늘도 이런 일이 있었어요.EF를 사용하여 AJAX 호출에 응답하여 엔티티를 반환했습니다.엔티티의 가상 속성으로 인해 서버에서 검출되지 않는 순환 종속성 오류가 발생했습니다.가상 속성에 [ScriptIgnore]속성을 추가하여 문제를 해결했습니다.
ScriptIgnore Atribute를 사용하는 대신 DTO를 반환하는 것이 좋습니다.
이 에러는 html/javascript에 내장된 PHP 에러에 의한 것일 수도 있습니다.예를 들어 다음과 같습니다.
<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}
PHP에 의해 html에 삽입된 코드의 등이 에러의 원인이 되지 않습니다.이러한 종류의 에러를 수정하려면(억제 경고), 처음에 이 코드를 사용했습니다.
error_reporting(E_ERROR | E_PARSE);
보려면 페이지의 "view source"를 마우스 오른쪽 버튼으로 클릭한 다음 완전한 html을 검토하여 이 오류를 확인합니다.
"Uncatched SyntaxError: 데이터가 잘못된 json 형식을 반환할 때 예기치 않은 토큰" 오류가 나타납니다. 경우에 따라 잘못된 json 형식을 알 수 없습니다.
alert(); function alert(); 를 사용하여 확인하십시오.
onSuccess : function(resp){
alert(resp);
}
입니다.존", "성" "도"입니다.
에 밑에 코드를 요.
onSuccess : function(resp){
var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp);
}
"Uncatched SyntaxError: "라는 out 오류가 발생하였습니다. 예기치 않은 토큰"
json 형식을 잘못 있는 형식.
::
...{"firstName":John", "lastName":Doe}
또는
Undefined variable: errCapt in .... on line<b>65</b><br/>{"firstName":"John", "lastName":"Doe"}
JSON.decode 또는 JSON.parse를 사용하기 전에 수정해 주세요.
를 express 404로 되어 있기 입니다./#요구를 할 수 있도록 .각도 라우터(j)가 요구를 처리할 수 있도록 한다. "js"에 입니다./#/whatever서버에 대해서 행해집니다.이것은, 단순한 요구입니다./, 전체 웹 페이지.
그래서 예를 들어, 제가 요청하고 싶은 것은/correct/somejsfile.js제가 잘못 입력해서/wrong/somejsfile.js서버에 대한 요구가 이루어집니다.해당 위치/파일이 존재하지 않기 때문에 서버는 다음과 같이 응답합니다.302 location: /#/wrong/somejsfile.js브라우저는 즐겁게 리다이렉트를 따르고 웹 페이지 전체가 반환됩니다.브라우저가 페이지를 js로 해석하면
학습되지 않은 구문 오류:예기치 않은 토큰 <
따라서 문제가 되는 경로/요구를 찾기 위해 302개의 요청을 검색합니다.
그게 도움이 됐으면 좋겠어요.
저도 같은 문제가 있었는데, 서버에서 돌아온 Json은 유효한 Json-P가 아니었습니다.콜을 크로스 도메인콜로서 사용하지 않는 경우는, 통상의 Json 를 사용합니다.
javascript의 url 주위에 단일/이중 인용문을 잊어버린 것이 실수입니다.
잘못된 코드는 다음과 같습니다.
window.location = https://google.com;
올바른 코드:
window.location = "https://google.com";
저 같은 경우에는 퍼팅/의 첫머리에src스크립트 또는href문제를 해결했습니다.
나는 "를 얻었다.SyntaxError: Unexpected token I사용했을 때jQuery.getJSON()부동소수점 값을 디컴라이즈하려고 하다Infinity, 로 부호화됩니다.INF이는 JSON에서는 불법입니다.
내 경우 mvc 컨트롤러의 매핑이 잘못되어 spring mvc 응용 프로그램을 실행하는 동안 동일한 오류가 발생했습니다.
@RequestMapping(name="/private/updatestatus")
위의 매핑을 로 변경했습니다.
@RequestMapping("/private/updatestatus")
또는
@RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)
저는 Chrome 브라우저의 페이지에서 소스를 볼 때 전구가 켜졌습니다.나는 if 스테이트먼트에 괄호를 하나 더 달았다.실패선 위에 십자가가 있는 빨간색 원이 바로 보일 것입니다.Uncaughted Synthe Uncaught Syntax Error:예기치 않은 토큰은 Chrome 콘솔에 처음 표시될 때 행 번호를 참조하지 않습니다.
내가 잘못했어
`var fs = require('fs');
var fs.writeFileSync(file, configJSON);`
이미 초기화를 완료했습니다.fs변수.하지만 다시 한 번 말하지만var두 번째 줄에.이것도 그런 오류를 주는데...
AngularJs 1.4.6 또는 이와 유사한 환경에서 이러한 현상이 발생하는 경우, 나의 템플릿은 Angular에서 찾을 수 없는 것이 문제입니다.왜냐하면, 파일 파일에는templateUrl(path) 제공한 항목을 찾을 수 없습니다.도달 가능한 경로만 제공하면 문제가 해결됩니다.
제 경우는 (존재하지 않는) URL이기 때문에, 2행째의 「송신」은 다른 것이 될 수 있습니다.
이 오류는 또한 다음 오류가 없음을 의미할 수 있습니다.colon또는:당신의 코드로.
JS 문제에 반복적으로 직면하여 저는 xblock 패키지에 Ckeditor를 적용하고 있습니다.누가 도와주면 제안해 주세요.OpenEdx, Javascript, xblock 사용
xblock.js:158 SyntaxError: Unexpected token '=>'
at eval (<anonymous>)
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at child.loadResource (xblock.js:236)
at applyResource (xblock.js:199)
at Object.<anonymous> (xblock.js:202)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at applyResource (xblock.js:201) "SyntaxError: Unexpected token '=>'\n at eval (<anonymous>)\n at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)\n at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)\n at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)\n at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)\n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)\n at Object.<anonymous> (http://localhost:18010/static/studio/bundles/commons.js:5057:25)\n at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)\n at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)\n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)"
파티에는 늦었지만 해결방법은 data Type을 json으로 지정하는 것이었습니다.또는 jsonp: true를 설정하지 마십시오.
스크립트 태그에 type 속성이 없기 때문에 이 오류가 발생하였습니다.
처음에 사용하고 있었는데 스크립트태그 안에 type 속성을 추가했더니 문제가 해결되었습니다.
학습되지 않은 구문 오류:예기치 않은 토큰}
Chrome에 의해 다음 샘플코드의 에러가 발생하였습니다.
<div class="file-square" onclick="window.location = " ?dir=zzz">
<div class="square-icon"></div>
<div class="square-text">zzz</div>
</div>
클릭을 고치고 해결했어요.
... onclick="window.location = '?dir=zzz'" ...
하지만 에러는 문제와는 무관합니다.
언급URL : https://stackoverflow.com/questions/3143698/uncaught-syntaxerror-unexpected-token
'programing' 카테고리의 다른 글
| 분리된 범위를 가진 지침에서 동작을 노출하려면 어떻게 해야 합니까? (0) | 2023.02.11 |
|---|---|
| Oracle에서 시간이 많이 걸리는 상위 5개의 SQL 쿼리 (0) | 2023.02.11 |
| MySQL에서 열려 있는 트랜잭션 표시 (0) | 2023.02.05 |
| Twitter Bootstrap의 data-toggle 속성 (0) | 2023.02.05 |
| htmlentity() vs. htmlspecialchars() (0) | 2023.02.05 |