我正在修改此处找到的教程:http ://www.w3schools.com/ajax/ajax_aspphp.asp ,以便将自动完成名称库存储在数据库中。我添加了一个按钮,如果该名称尚未在数据库中,则该按钮允许用户将名称添加到数据库中。当我单击按钮时,该方法会触发,但是 addName() 方法中指定的 php 脚本不会执行。这很奇怪,因为 showHint() 方法中定义的脚本确实会执行。这是我的javascript(这是所有需要显示的内容)。我省略了脚本:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
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","gethint.php?q="+str,true);
xmlhttp.send();
}
function addName(str){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","addName.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
<button type="button" onclick="addName(document.getElementById('txt1').value)">Add Name</button>
</body>
</html>