简体   繁体   English

语法错误:意外的令牌

[英]syntax error: unexpected token <

I've tried many things and there's no way, always appears this error I tried to use only one option to see if passed, changed the call of jquery, but not.我已经尝试了很多事情,但没有办法,总是出现这个错误我试图只使用一个选项来查看是否通过,更改了 jquery 的调用,但没有。

I looked in various places on the internet about this error, but could not solve or understand why it is happening.我在互联网上的各个地方查看了有关此错误的信息,但无法解决或理解它为什么会发生。 On my pc using EasyPHP works perfectly, but when I put online does not work.在我的电脑上使用 EasyPHP 工作得很好,但是当我上网时却不起作用。

Syntax Error: unexpected token <语法错误:意外标记 <

Here's my code:这是我的代码:

$(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

This usually happens when you're including or posting to a file which doesn't exist.当您包含或发布到不存在的文件时,通常会发生这种情况。 The server will return a regular html-formatted "404 Not Found" enclosed with服务器将返回一个常规的 html 格式的“404 Not Found”,其中包含

'<html></html>' 

tags.标签。 That first chevron < isn't valid js nor valid json, therefore it triggers an unexpected token.第一个 chevron < 不是有效的 js 也不是有效的 json,因此它触发了一个意外的标记。

What if you try to change 'funcoes/enquete_adm.php' to an absolute url, just to be sure?如果您尝试将 'funcoes/enquete_adm.php' 更改为绝对 url,只是为了确定会怎样?

EDIT (several years later)编辑(几年后)

The root cause might not always come from 404 errors.根本原因可能并不总是来自 404 错误。 Sometimes you can make a request to an API and receive HTML formatted errors.有时,您可以向 API 发出请求并收到 HTML 格式的错误。 I've stumbled to a couple of cases in which the API endpoint should have returned我偶然发现了 API 端点应该返回的几种情况

{
   error: "you must be authenticated to make this request"
}

With header 401. And instead I got使用标题 401。相反,我得到了

<html>You must be authenticated to make this request</html>

With header 200.带有标题 200。

Given the header is 200 you can't tell the request has failed beforehand, and you're stuck to try and JSON.parse the response to check if it's valid.鉴于标头是 200,您无法事先判断请求已失败,并且您不得不尝试使用JSON.parse来检查响应是否有效。

You have unnecessary ;你有不必要的; (semicolons): (分号):

Example here:这里的例子:

 }else{
        $('#resposta').addClass('warning-box').html('É necessário no mínimo duas opções');
    };

The trailing ;尾随; after } is incorrect. }之后是不正确的。

Another example here:这里的另一个例子:

}else{
    $('#resposta').addClass('warning-box').html('Coloque a pergunta da enquete');
};

I suspect you're getting text/html encoding in response to your request so I believe the issue is:我怀疑您收到了 text/html 编码以响应您的请求,所以我认为问题是:

dataType : 'json',

try changing it to尝试将其更改为

dataType : 'html',

From http://api.jquery.com/jQuery.get/ :http://api.jquery.com/jQuery.get/

dataType Type: String The type of data expected from the server. dataType 类型:字符串 预期来自服务器的数据类型。 Default: Intelligent Guess (xml, json, script, or html).默认值:智能猜测(xml、json、脚本或 html)。

The error SyntaxError: Unexpected token < likely means the API endpoint didn't return JSON in its document body, such as due to a 404.错误SyntaxError: Unexpected token <可能意味着 API 端点未在其文档正文中返回 JSON,例如由于 404。

In this case, it expects to find a { (start of JSON);在这种情况下,它希望找到一个{ (JSON 的开始); instead it finds a < (start of a heading element).相反,它找到一个< (标题元素的开始)。

Successful response:成功回复:

<html>
  <head></head>
  <body>
    {"foo": "bar", "baz": "qux"}
  </body>
</html>

Not-found response:未找到 回复:

<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>

Try visiting the data endpoint's URL in your browser to see what's returned.尝试在浏览器中访问数据端点的 URL 以查看返回的内容。

I had a similar problem, and my issue was that I was sending javascript to display console messages.我有一个类似的问题,我的问题是我正在发送 javascript 来显示控制台消息。

Even when I looked at the file in my browser (not through the application) it showed exactly as I expected it to (eg the extra tags weren't showing), but there were showing in the html/text output and were trying to be parsed.即使我在浏览器中(不是通过应用程序)查看文件时,它也完全按照我的预期显示(例如,没有显示额外的标签),但是在 html/text 输出中显示并试图解析。

Hope this helps someone!希望这可以帮助某人!

I suspect one of your scripts includes a source map URL .我怀疑您的脚本之一包含源映射 URL (Minified jQuery contains a reference to a source map, for example.) (例如,缩小的 jQuery 包含对源映射的引用。)

When you open the Chrome developer tools, Chrome will try to fetch the source map from the URL to aid debugging.当您打开 Chrome 开发者工具时,Chrome 会尝试从 URL 中获取源映射以帮助调试。 However, the source map does not actually exist on your server, but you are instead sent a regular 404 page containing HTML.但是,源映射实际上并不存在于您的服务器上,而是向您发送了一个包含 HTML 的常规 404 页面。

This error can also arise from a JSON AJAX call to a PHP script that has an error in its code.此错误也可能由对代码中存在错误的 PHP 脚本的 JSON AJAX 调用引起。 Servers are often set up to return PHP error information formatted with html markup.服务器通常设置为返回用 html 标记格式化的 PHP 错误信息。 This response is interpreted as invalid JSON, resulting in the "unexpected token <" AJAX error.此响应被解释为无效的 JSON,从而导致“意外令牌 <”AJAX 错误。

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.要使用 Chrome 查看 PHP 错误,请转到 Web 检查器中的“网络”面板,单击左侧列出的 PHP 文件,然后单击“响应”选项卡。

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通过 ajax 发布时,首先正常提交总是一个好主意,以确保被调用的文件始终返回有效数据 (json) 并且没有html标签或其他错误

<form action="path/to/file.php" id="ajaxformx">

By adding x to id value, jquery will not process it.通过将 x 添加到 id 值,jquery 不会处理它。

Once you are sure everything is fine then remove the x from id="ajaxform" and the empty the action attribute value一旦你确定一切正常,然后从id="ajaxform"删除x并清空action属性值

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.我也有syntax error: unexpected token <通过 ajax 发布表单时。 Then I used curl to see what it returns:然后我使用 curl 来查看它返回的内容:

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我检查了所有包含的 JS 路径

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>

从我的代码中删除这一行解决了我的问题。

header("Content-Type: application/json; charset=UTF-8"); 

Just ignore parameter passing as a false in java script functions只需忽略在 java 脚本函数中作为 false 传递的参数

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避免编写 locationId= false 类型的语句,因为这会在 chrome 和 IE 中产生错误

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.我通过 node/express/jade 提供服务,并且已经移植了一个旧的 jade 文件。 One of the lines was to not bork when Typekit failed:当 Typekit 失败时,其中一条线是不要无聊:

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.简单,但很棘手。

This happened to me with a page loaded in via an iframe.这发生在我身上,通过 iframe 加载了一个页面。 The iframe src page had a 404 script reference. iframe src 页面有一个 404 脚本引用。 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确保您不包括 jquery 代码之间

< script > < /script > <脚本> </脚本>

If so remove that and code will work fine, It worked in my case.如果是这样,删除它并且代码将正常工作,它在我的情况下工作。

For me ,none of the solutions above worked so I had to deeply investigate the source of my problem and I ended up on router path .对我来说,上面的解决方案都没有奏效,所以我不得不深入调查我的问题的根源,最后我发现了router path

Please check the way your paths { path:"/register/onboard" ... } did not work but { path:"/register_onboard" ... } did.请检查您的路径{ path:"/register/onboard" ... }{ path:"/register_onboard" ... }不起作用。 So I don't know why maybe it's a bag .所以我不知道为什么它可能是一个包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM