[英]Ajax submit using a button
我正在使用此頁面中的代碼: 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>
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();
}
他們將事件附加到選擇,因此您可以將其移動到表單
<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>
編輯:
哦,並添加一個提交按鈕
像這樣的東西:
<!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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.