使用 Chrome:未捕获的语法错误:意外的标记 <
我从 chrome 收到此错误 Uncaught SyntaxError: Unexpected token < 但在 FireFox 上一切正常。 我发现了很多类似的帖子,但没有解决方案。
所以我想知道是否有一种方法可以在构建第二个页面后将其发送到浏览器,并使用它自己的标头。 当我看到 Firefox 将我在下面的函数中回显的内容放在 html 结束标记 之后,而 Chrome 将其放置在结束标记之前时,我就产生了这个想法。
基本上,我喜欢按这个顺序发送:
header('Content-Type: text/html; charset= utf-8');
<html></html>
header('Content-Type: text/javascript; charset= utf-8');
<script></script>
这是我的 php 脚本,我想取消注释标头代码并独立于 html 页面发送它。
public static function jsShow($html)
{
//header('Content-Type: text/javascript; charset= utf-8');
echo "
<script type=\"text/javascript\">
var e = document.getElementById('message');
e.innerHTML = $html ;
e.style.display = 'block';
</script>";
}
这就是页面在 Firefox 中的样子,并且有效:
</body>
</html>
<script type="text/javascript">
var e = document.getElementById('message');
e.innerHTML = <ul style="list-style: none; margin: 0; padding: 0;">
<li style="background-color: #0000FF; margin: 0;"><img src="/asset/icon/info.gif" alt="Info: " /> working</li>
<li style="background-color: #008000; margin: 0;"><img src="/asset/icon/success.gif" alt="Success: " /> Got it</li>
</ul>
;
e.style.display = 'block';
</script>
我想我也许可以使用 ob_start() & ob_end_flush(),但您无法仅使用该内容来控制标头。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
...
...
错误“未捕获的语法错误:意外的标记 <”对于您在第二个代码块中显示的内容来说,这是一个适当的错误,因为它是无效的 JavaScript,并且应该在所有浏览器中失败。您正在将
e.innerHTML
指定为等于不带引号的字符串:请参阅“<”就在“=”之后? ——那是意想不到的令牌。
您似乎没有在该字符串中使用任何单引号,因此最简单的解决方法是将其用单引号引起来。我不知道 PHP,但类似这样:
或者无论 PHP 语法是什么,都可以将此结果返回到浏览器:
顺便说一句,为同一响应设置两个不同的标头是没有意义的。您返回的是一个 html 页面,该页面恰好在底部有一个脚本块。 “text/javascript”内容类型更适合链接的 JS 文件,这些文件不包含 html(无脚本标签),仅包含 JS。
The error "Uncaught SyntaxError: Unexpected token <" is an appropriate error for what you are showing in your second code block, because it is invalid JavaScript and should fail in all browsers. You are assigning
e.innerHTML
equal to an unquoted string:See the "<" right after the "="? - that is the unexpected token.
You don't seem to use any single quotes within that string, so the simplest fix is just to wrap it in single quotes. I don't know PHP, but something like this:
Or whatever the PHP syntax is to get this result returned to the browser:
By the way, it doesn't make sense to set two different headers for the same response. What you are returning is one page that is html, which happens to have a script block at the bottom. The "text/javascript" content type is more for linked JS files, which do not contain html (no script tags), just JS.