我有简单的代码,可以在不使用 javascript 刷新页面的情况下将值插入数据库。问题是,当我在方法中使用“onchange”属性来调用函数时,代码可以正常工作并插入值但是当我删除“onchange”表单并使用按钮“onclick”属性来调用相同的方法时,它可以运行一次并且然后停止工作。
我的comment.html文件的代码是
<html>
<head>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form method="GET">
<input type="text" name="q">
<button method="GET" onclick="showUser(q.value)">Submit</button>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
我的getuser.php文件的代码是:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','login');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql2= "INSERT INTO `users` ( `FirstName`) VALUES( '{$_GET['q']}') ";
$result = mysqli_query($con,$sql2);
while($row = $result)
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>