jQuery 语法错误:意外标记 <

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18561556/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:57:13  来源:igfitidea点击:

syntax error: unexpected token <

javascriptjqueryajaxsyntaxtoken

提问by Geovane Krüger

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

回答by ffflabs

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. Sometimes you can make a request to an API and receive HTML formatted errors. I've stumbled to a couple of cases in which the API endpoint should have returned

根本原因可能并不总是来自 404 错误。有时,您可以向 API 发出请求并收到 HTML 格式的错误。我偶然发现了 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.parsethe response to check if it's valid.

鉴于标头是 200,您无法事先判断请求已失败,并且您不得不尝试和JSON.parse响应来检查它是否有效。

回答by happyhuman

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');
};

回答by StylusEater

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. Default: Intelligent Guess (xml, json, script, or html).

dataType 类型:字符串 预期来自服务器的数据类型。默认值:智能猜测(xml、json、脚本或 html)。

回答by 2540625

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); instead it finds a <(start of a heading element).

在这种情况下,它希望找到一个{(JSON 的开头);相反,它找到一个<(标题元素的开始)。

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 以查看返回的内容。

回答by Chloe

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!

希望这可以帮助某人!

回答by user2428118

I suspect one of your scripts includes a source map URL. (Minified jQuery contains a reference to a source map, for example.)

我怀疑您的脚本之一包含源映射 URL。(例如,缩小的 jQuery 包含对源映射的引用。)

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.

当您打开 Chrome 开发者工具时,Chrome 会尝试从 URL 中获取源映射以帮助调试。但是,源映射实际上并不存在于您的服务器上,而是向您发送了一个包含 HTML 的常规 404 页面。

回答by eirikarvey

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.

此错误也可能由对代码中存在错误的 PHP 脚本的 JSON AJAX 调用引起。服务器通常设置为返回用 html 标记格式化的 PHP 错误信息。此响应被解释为无效的 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 文件,然后单击“响应”选项卡。

回答by Onimusha

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 htmltags 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 xfrom id="ajaxform"and the empty the actionattribute value

一旦确定一切正常,然后删除xfromid="ajaxform"并清空action属性值

This is how I sorted the same error for myself just a few minutes ago :)

这就是我几分钟前为自己整理相同错误的方式:)

回答by sadaf2605

I was also having syntax error: unexpected token <while posting a form via ajax. Then I used curl to see what it returns:

我也在syntax error: unexpected token <通过ajax发布表单时遇到了问题。然后我使用 curl 来查看它返回的内容:

curl -X POST --data "firstName=a&lastName=a&[email protected]&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);

回答by omar nazzal

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>