我正在修改在这里找到的教程: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>
像这样:
function getXhr() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, FF, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function showHint(str) {
var xmlhttp;
if (str.length==0) {
document.getElementById("txtHint").innerHTML="";
return;
}
xmlhttp = getXhr();
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 = getXhr();
xmlhttp.onreadystatechange= function() {
...your logic here...
};
xmlhttp.open("GET","addName.php?q="+str, true);
xmlhttp.send();
}
添加一个 onreadystatechange 并查看 http 状态调用,看看它是否是一个错误。
使用像Fiddler或Firebug这样的工具来查看请求是否发出。
你应该对str
进行网址编码。
请以这种方式更改您的代码
<form action="">
First name: <input type="text" id="txt1" value="ABC-XYZ" onkeyup="showHint(this.value)" />
</form>