[英]Query database with Ajax and classic ASP
我正在尝试从w3scools修改脚本,以结合使用asp和ajax来查询数据库并返回结果。
这是代码:
<html>
<head>
<script type="text/javascript">
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" onchange="showCustomer(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
</select>
</form>
<br />
<div id="txtHint">Customer info will be listed here...</div>
</body>
</html>
我想将select字段替换为2个输入字段。
有人可以告诉我如何修改javascript,以便输入值和querystring一起传递,以及需要在表单上更改哪些内容以调用函数。
谢谢
这完全取决于您希望页面如何操作。 你能更具体一点吗?
当您说“输入值”时,您的意思是一个文本框?
在下面的示例中,我假设您将有两个字段和一个提交按钮:
<form action="">
<label for="MyTextBox1>Enter some text:</label>
<input type="text" id="MyTextBox1" />
<label for="MyTextBox1>Enter some text:</label>
<input type="text" id="MyTextBox2" />
<input type="button" onclick="showCustomer();" />
</form>
您的JavaScript函数的定义将从
function showCustomer(str)
至
function showCustomer()
而且,您需要删除所有关联的str
代码。
要获取这些值,请使用document.getElementById
:
var val1 = document.getElementById("MyTextBox1").value);
var val2 = document.getElementById("MyTextBox1").value);
xmlhttp.open("GET","getcustomer.asp?q="+ val1 +"&r=" + val2 ,true);
这很粗糙而且已经准备好,但是是一个很好的起点。
取决于你想怎么做。 现在,脚本本身是由select
元素的change事件触发的。 如果替换该元素,则将需要其他事件来触发脚本。 一个按钮,也许? 如果是这样,那么可能最简单的方法是使用jQuery:
Field 1: <input id="text1" type="text" />
Field 2: <input id="text2" type="text" />
<input id="buttonSend" type="button" value="Send" />
<script type="text/javascript">
$(document).ready(function() {
$('#buttonSend').click(function() {
$.get('getcustomer.asp?text1=' +
$('#text1').val() + '&text2=' + $('#text2').val()
);
});
});
</script>
$.get()
函数可以做更多的事情,在此处记录 ,实际上只是$.ajax()
函数的简写,在这里记录 。 前者较短,后者为您提供更多选择和控制。
(还请注意,如果您还想使用其他JavaScript库,则可能希望在上面的代码中将$
别名替换为jQuery
以避免混淆。)
注意这里的一个好处是它将脚本(如果需要,可以将其放在单独的文件中)与标记分离。 作为整体设计范例,通常比标记中的onchange="someFunctionCall()"
语法更onchange="someFunctionCall()"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.