小编典典

使用Ajax和经典ASP查询数据库

ajax

我正在尝试从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一起传递,以及需要在表单上更改哪些内容以调用函数。

谢谢


阅读 317

收藏
2020-07-26

共1个答案

小编典典

这完全取决于您希望页面如何操作。您能更具体一点吗?

当您说“输入值”时,您的意思是一个文本框?

在下面的示例中,我假设您将有两个字段和一个提交按钮:

<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);

这很粗糙而且已经准备好,但是是一个很好的起点。

2020-07-26