1

我有简单的代码,可以在不使用 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);
?>
4

2 回答 2

2

代码是正确的,除了您创建的按钮。

利用:<input type="button" onclick="showUser(q.value)" value="Submit">

代替:<button method="GET" onclick="showUser(q.value)">Submit</button>

您所做的实际上是提交表单。因此,onclick 事件被覆盖。

于 2013-09-20T23:52:15.633 回答
0

@Lavneet 方向正确,但没有解决问题。

如果您坚持false该设置,则必须返回onclick

<button onclick="showUser(q.value);return false;">Submit</button>

这样,表格不会在之后重新提交showUser()

于 2013-09-20T23:59:02.510 回答