我已经多次检查了我的代码,它似乎无法正常工作,因为PHP运行它只是在浏览器控制台中显示以下错误:
Uncaught SyntaxError:意外的标识符。
我不确定这只是一个简单的问题,还是有更多问题。
<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>';
}
}
}
答案 0 :(得分:0)
问题在于脚本标记字符串。
如果您检查输出的<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中查看转义单引号分隔符方法的演示。