我正在使用此页面中的代码:http://www.w3schools.com/ajax/ajax_database.asp来构建我的ajax解决方案。
我到了那里,但是这段代码使用了onchange
,我想用一个按钮来提交。
我的一次尝试:
<!DOCTYPE html>
<html>
<head>
<script>
function showCustomer(str)
{
var xmlhttp;
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","getcustomer.asp?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="">
<select name="customers">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
<input name="Submit1" type="submit" onclick="showCustomer(this.value)" />
</form>
<br>
<div id="txtHint">Customer info will be listed here...</div>
</body>
</html>
答案 0 :(得分:1)
onchange是select元素的一个事件。
将该事件绑定到按钮元素中。
<button onclick="showCustomer()">Submit</button>
然后在showCustomer()方法中获取所需的客户
function showCustomer()
{
var str = document.getElementById("customers").value;
.
.
.
xmlhttp.open("GET","getcustomer.asp?q="+str,true);
xmlhttp.send();
}
答案 1 :(得分:1)
他们将事件附加到选择,因此您可以将其移动到表单
<form action="" onsubmit="showCustomer(document.getElementById('customers')).value);return false">
<select id="customers" name="customers">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
<input type="submit"/>
</form>
编辑:
哦,然后添加一个提交按钮
答案 2 :(得分:0)
类似的东西:
<!DOCTYPE html>
<html>
<head>
<script>
function showCustomer()
{
var xmlhttp;
var str = document.getElementById("customers").value;
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","getcustomer.asp?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<select name="customers">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
<input name="Submit1" type="button" onclick="showCustomer()" />
<br>
<div id="txtHint">Customer info will be listed here...</div>
</body>
</html>
但您应该尝试Jquery以避免使用详细的语法document.getElementById