我有简单的代码,可以使用javascript将值插入数据库而无需刷新页面。 问题是,当我在方法中使用“onchange”atrribute来调用函数时,代码工作正常并且插入了值但是当我删除“onchange”表单并使用Button“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);
?>
答案 0 :(得分:2)
代码是正确的。
使用:<input type="button" onclick="showUser(q.value)" value="Submit">
代替:<button method="GET" onclick="showUser(q.value)">Submit</button>
您所做的实际上是提交表单。因此,onclick事件正在被覆盖。
答案 1 :(得分:0)
@Lavneet是正确的方向,但没有解决问题。
如果您坚持该设置,则必须在false
中返回onclick
:
<button onclick="showUser(q.value);return false;">Submit</button>
因此,表格不会在showUser()
之后重新提交。