我已经多次检查我的代码,但它似乎无法正常工作,因为当 PHP 运行时,它只是在浏览器控制台中显示以下错误:
Uncaught SyntaxError: Unexpected identifier.
我不确定这只是一个简单的问题还是有更多问题。
<div class="alert alert-success" role="alert"><h4 id="Txt"> Now In Development</h4></div>
<form method="POST" action="#goHere">
<input type="email" name="email" placeholder="Enter Email For Updates">
<input type="submit" name="submit">
</form>
if(isset($_POST['submit'])) {
$email = htmlentities(strip_tags($_POST['email']));
$logname = 'list/email.txt';
$logcontents = file_get_contents($logname);
$searchfor = $email;
// the following line prevents the browser from parsing this as HTML.
//header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($logname);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
$filecontents = $email."\r\n";
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fileopen,$filecontents);
$fileclose = fclose($fileopen);
if($email == NULL) {
echo '<Script> document.getElementById("Txt").innerHTML = "<div class="alert alert-danger" role="alert">"You entered Nothing</div>"; </script>';
} elseif(preg_match_all($pattern, $contents, $matches)){
echo '<Script> document.getElementById("Txt").innerHTML = "<div class="alert alert-success" role="alert">Email was already added</div>"; </script>';
} else {
if(!$fileopen or !$filewrite or !$fileclose) {
echo '<Script> document.getElementById("Txt").innerHTML = "Thankyou"; </script>';
} else {
echo '<Script> document.getElementById("Txt").innerHTML = "<div class="alert alert-success" role="alert">Email Succefully Added"; </script>';
}
}
}
最佳答案
问题
问题出在脚本标签字符串上。
如果您检查输出的 <script>
标记,您可能会看到类似这样的内容:
<script> document.getElementById("Txt").innerHTML = "<div class="alert alert-success" role="alert">Email was already added</div>"; </script>
请注意,双引号不会在 HTML 中转义。
可能的解决方案
解决这个问题的一种方法是转义 HTML 中的双引号:
echo '<Script> document.getElementById("Txt").innerHTML = "<div class=\"alert alert-success\" role=\"alert\">Email was already added</div>"; </script>';
或者使用转义单引号分隔 HTML:
echo '<Script> document.getElementById("Txt").innerHTML = \'<div class="alert alert-success" role="alert">Email was already added</div>\'; </script>';
其他选项包括 heredoc或者可能nowdoc格式或模板引擎。
请参阅 this phpfiddle 中的转义单引号定界符方法的演示。 .
关于javascript - Php/Javascript 未捕获语法错误 : Unexpected identifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46802821/