我有一个可以发布故事的网站。有一个表单,当用户提交表单时,必须检查是否存在具有相同标题的故事 - 如果是,则阻止表单提交。表格和检查功能:
if (!isset($_SESSION[username]))
echo "<br>You are not logged in";
else echo "
<form method='get' action='storyupload2.php' onsubmit='return checkTitle(); return false; '>
<input id='titleInput' type='text' name='title' placeholder='Title (maximum 200 characters)' maxlength='200' size='200' required><br>
<textarea name='story' placeholder='Story (you can use HTML tags)' rows='33' cols=200 maxlength='10000' required onkeyup=countchars(this)></textarea>
<div id='counter'></div>
<input type='submit' value='Post'>
<span id='error'></span>
</form>"
?>
function checkTitle() {
var title=document.getElementById('titleInput')
var value=title.value;
var result=false
var request=new XMLHttpRequest()
request.onreadystatechange=function () {
if(request.readyState==4 && request.status==200)
{
result=JSON.parse(request.responseText);
console.log(result)
if(result==true)
{
var span=document.getElementById('error')
span.innerHTML='Story with such title exists. Write a different title';
return false;
}
return true
}
}
request.open("GET",'checktitle.php?t='+value,true)
request.send()
}
问题是该函数抛出SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
错误。但是如果我删除'return'所以它只是onsubmit='checkTitle(); return false;'
,那么该函数可以正常工作。 php文件执行检查:
<?php
include 'constants.php';
$storytitle=$_GET['t'];
//echo $storytitle."\n";
$con=new mysqli('',databaseuser,databasepassword,database);
$q="SELECT title FROM Stories";
$r=$con->query($q);
while($row=$r->fetch_array())
{
$existingtitle=$row[0];
if($existingtitle==$storytitle)
{
echo json_encode(true);
exit();
}
}
echo json_encode(false);
我已经搜索了很长时间的解决方案,但还没有想出来。