[英]Php-javascript code working only once
我有簡單的代碼,無需使用javascript刷新頁面即可將值插入數據庫。 問題是,當我在方法中使用“ onchange”屬性來調用函數時,代碼可以正常工作並插入了值,但是當我刪除“ 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);
?>
代碼是正確的,除了您創建的按鈕。
使用: <input type="button" onclick="showUser(q.value)" value="Submit">
而不是: <button method="GET" onclick="showUser(q.value)">Submit</button>
您所做的實際上是提交表單。 因此,onclick事件被覆蓋。
@Lavneet方向正確,但不能解決問題。
如果您堅持該設置,則必須在onclick
返回false
:
<button onclick="showUser(q.value);return false;">Submit</button>
因此,不會在showUser()
之后重新提交showUser()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.