구문 오류 : 예기치 않은 토큰 <
나는 많은 것을 시도했지만 방법이 없습니다. 항상이 오류가 나타납니다.이 오류는 통과했는지 확인하기 위해 하나의 옵션 만 사용하려고했지만 jquery 호출을 변경했습니다.
이 오류에 대해 인터넷의 여러 곳을 살펴 보았지만 왜 발생하는지 해결하거나 이해할 수 없었습니다. EasyPHP를 사용하는 내 PC에서는 완벽하게 작동하지만 온라인으로 전환하면 작동하지 않습니다.
구문 오류 : 예기치 않은 토큰 <
내 코드는 다음과 같습니다.
$(function(){
$('#salvar').click(function(){
var key = 'salvar';
var title = $('#title').val();
var opcao1 = $('#opcao1').val();
var opcao2 = $('#opcao2').val();
var opcao3 = $('#opcao3').val();
var opcao4 = $('#opcao4').val();
var opcao5 = $('#opcao5').val();
var opcao6 = $('#opcao6').val();
if(title.length > 0){
if(opcao2.length > 0){
$('#resposta').removeClass().html('Salvando a enquete...<br clear="all"><br><img src="images/switch-loading.gif" />');
$.ajax({
type : 'POST',
url : 'funcoes/enquete_adm.php',
dataType : 'json',
data: {key:key,title:title,opcao1:opcao1,opcao2:opcao2,opcao3:opcao3,opcao4:opcao4,opcao5:opcao5,opcao6:opcao6},
success : function(data){
if(data.sql == 'ok'){
$('#resposta').addClass('success-box').html('Enquete Salva!').fadeIn(1000);
$('#control').fadeOut();
}else if(data.sql == 'error'){
$('#resposta').addClass('info-box').html('Ops, aconteceu um erro. Por favor, tente novamente').fadeIn(1000);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest " + XMLHttpRequest[0]);alert(" errorThrown: " + errorThrown);alert( " textstatus : " + textStatus);
}
});
}else{
$('#resposta').addClass('warning-box').html('É necessário no mínimo duas opções');
};
}else{
$('#resposta').addClass('warning-box').html('Coloque a pergunta da enquete');
};
return false;
});
}); // End
이는 일반적으로 존재하지 않는 파일을 포함하거나 게시 할 때 발생합니다. 서버는 다음으로 묶인 일반 html 형식의 "404 Not Found"를 반환합니다.
'<html></html>'
태그. 첫 번째 chevron <은 유효한 js도 아니고 유효한 json도 아니므로 예기치 않은 토큰이 트리거됩니다.
'funcoes / enquete_adm.php'를 절대 URL로 변경하려고하면 어떻게됩니까?
편집 (수년 후)
근본 원인이 항상 404 오류에서 오는 것은 아닙니다. 때때로 API를 요청하고 HTML 형식 오류를 수신 할 수 있습니다. API 엔드 포인트가 반환되어야하는 몇 가지 경우를 발견했습니다.
{
error: "you must be authenticated to make this request"
}
헤더 401로. 그리고 대신에
<html>You must be authenticated to make this request</html>
헤더 200 포함.
헤더가 200이면 미리 요청이 실패했음을 알 수 없으며 JSON.parse유효한지 확인 하기 위해 시도하고 응답해야합니다.
불필요한 ;(세미콜론) :
여기에 예 :
}else{
$('#resposta').addClass('warning-box').html('É necessário no mínimo duas opções');
};
후행는 ;후 }올바르지 않습니다.
여기에 또 다른 예 :
}else{
$('#resposta').addClass('warning-box').html('Coloque a pergunta da enquete');
};
귀하의 요청에 대한 응답으로 텍스트 / html 인코딩을 받고 있다고 생각하므로 문제는 다음과 같습니다.
dataType : 'json',
그것을 변경해보십시오
dataType : 'html',
에서 http://api.jquery.com/jQuery.get/ :
dataType 유형 : 문자열 서버에서 예상되는 데이터 유형입니다. 기본값 : Intelligent Guess (xml, json, 스크립트 또는 html).
이 오류 SyntaxError: Unexpected token <는 API 엔드 포인트가 404로 인해 문서 본문에 JSON을 반환하지 않았 음을 의미 할 수 있습니다.
이 경우 {(JSON의 시작) 을 찾을 것으로 예상합니다 . 대신 <(표제 요소의 시작)을 찾습니다 .
성공적인 응답 :
<html>
<head></head>
<body>
{"foo": "bar", "baz": "qux"}
</body>
</html>
찾을 수없는 응답 :
<html>
<head></head>
<body>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
</body>
</html>
브라우저에서 데이터 엔드 포인트의 URL을 방문하여 반환 된 내용을 확인하십시오.
비슷한 문제가 있었고 내 문제는 콘솔 메시지를 표시하기 위해 자바 스크립트를 보내는 것입니다.
응용 프로그램을 통하지 않고 내 브라우저에서 파일을 보았을 때도 예상했던대로 정확하게 표시되었지만 (예 : 추가 태그가 표시되지 않음) html / text 출력에 표시되고있었습니다. 파싱.
Hope this helps someone!
I suspect one of your scripts includes a source map URL. (Minified jQuery contains a reference to a source map, for example.)
When you open the Chrome developer tools, Chrome will try to fetch the source map from the URL to aid debugging. However, the source map does not actually exist on your server, but you are instead sent a regular 404 page containing HTML.
This error can also arise from a JSON AJAX call to a PHP script that has an error in its code. Servers are often set up to return PHP error information formatted with html markup. This response is interpreted as invalid JSON, resulting in the "unexpected token <" AJAX error.
To view the PHP error using Chrome, go to the Network panel in the web inspector, click the PHP file listed on the left side, and click on the Response tab.
When posting via ajax, it's always a good idea to first submit normally to ensure the file that's called is always returning valid data (json) and no errors with html tags or other
<form action="path/to/file.php" id="ajaxformx">
By adding x to id value, jquery will not process it.
Once you are sure everything is fine then remove the x from id="ajaxform" and the empty the action attribute value
This is how I sorted the same error for myself just a few minutes ago :)
I was also having syntax error: unexpected token < while posting a form via ajax. Then I used curl to see what it returns:
curl -X POST --data "firstName=a&lastName=a&email=array@f.com&pass=aaaa&mobile=12345678901&nID=123456789123456789&age=22&prof=xfd" http://handymama.co/CustomerRegistration.php
I got something like this as a response:
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>3</b><br />
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>4</b><br />
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>7</b><br />
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>8</b><br />
So all I had to do is just change the log level to only errors rather than warning.
error_reporting(E_ERROR);
i checked all Included JS Paths
Example Change this
<script src="js/bootstrap.min.js" type="text/javascript"></script>
TO
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>
Removing this line from my code solved my problem.
header("Content-Type: application/json; charset=UTF-8");
Just gonna throw this in here since I encountered the same error but for VERY different reasons.
I'm serving via node/express/jade and had ported an old jade file over. One of the lines was to not bork when Typekit failed:
script(type='text/javascript')
try{Typekit.load();}catch(e){}
It seemed innocuous enough, but I finally realized that for jade script blocks where you're adding content you need a .:
script(type='text/javascript').
try{Typekit.load();}catch(e){}
Simple, but tricky.
Just ignore parameter passing as a false in java script functions
Ex:
function getCities(stateId,locationId=false){
// Avoid writting locationId= false kind of statements
/*your code comes here*/
}
Avoid writting locationId= false kind of statements, As this will give the error in chrome and IE
This happened to me with a page loaded in via an iframe. The iframe src page had a 404 script reference. Obviously I couldn't find the script reference in the parent page, so it took me a while to find the culprit.
make sure you are not including the jquery code between the
< script > < /script >
If so remove that and code will work fine, It worked in my case.
참고URL : https://stackoverflow.com/questions/18561556/syntax-error-unexpected-token
'program story' 카테고리의 다른 글
| Rails에서 다 대다 관계 생성 (0) | 2020.11.20 |
|---|---|
| Apache httpd 용 mod_ssl을 설치하는 방법은 무엇입니까? (0) | 2020.11.20 |
| 빠른. (0) | 2020.11.20 |
| 서비스 의도는 명시 적이어야 함 : 의도 (0) | 2020.11.20 |
| Swift에서 NSException 잡기 (0) | 2020.11.20 |