Autocompletar ASP clasico, AJAX y Javascript
Código ASP clásico
- Por Programador ASP clásico /
- 03/06/2014 @ 09:50:32 /
- 1014 visitas
A continuación se muestra un código en ASP clásico para autocompletar (suggest) registros de una base de datos en Access o en SQL Server. Para ello utilizaremos Ajax- y Javascript:
<%
response.expires=-1
Dim rsWords, rsWords_numRows, q, b, hint
q=ucase(request.querystring("q"))
b=(request.querystring("b"))
f=(request.querystring("f"))
a=(request.querystring("a"))
hint=""
Set rsWords = Server.CreateObject("ADODB.Recordset")
rsWords.ActiveConnection = <connection string>
rsWords.Source = "SELECT medName FROM dbo.prescMeds WHERE (medName LIKE'" + q + "%') ORDER BY medName"
rsWords.CursorType = 2
rsWords.CursorLocation = 2
rsWords.LockType = 3
rsWords.Open()
rsWords_numRows = 5
If Not rsWords.EOF Then
Do While Not rsWords.EOF
If trim(hint) = "" Then
hint = "<a href=""javascript:setTextBox('" & rsWords("medName") & "','" & b & "','" & f & "','" & a & "');"">" & rsWords("medName") & "</a>"
Else
hint = hint & " <br /><br /> <a href=""javascript:setTextBox('" & rsWords("medName") & "','" & b & "','" & f & "','" & a & "');"">" & rsWords("medName") & "</a>"
End If
rsWords.MoveNext()
Loop
End If
if trim(hint)="" then
response.write("no suggestion")
else
response.write(hint)
end if
rsWords.Close()
Set rsWords = Nothing
%>
El código Javascript/AJAX para procesar las sugerencias es el siguiente:
var xmlHttp
function showHint(str, box, thisForm, autoSubmit)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="gethint.asp";
url=url+"?q="+str;
url=url+"&b="+box;
url=url+"&f="+thisForm;
url=url+"&a="+autoSubmit;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
//this function allows for Clickable suggestions
function setTextBox(thisText,thisBox,thisForm,autoSubmit)
{
document.getElementById(thisBox).value = thisText
//this autoSubmits the form after a suggestion is clicked - it is not working :(
//if(autoSubmit=='true'){
// alert(thisForm);
// document.getElementById(thisForm).submit();
//
}
}
El código html que usará el script de ASP clásico y el de Javascript / Ajax es el siguiente:
<form action="prescriptions4.asp" method="post">
<input type="text" id="txt1" onkeyup="showHint(this.value,'txt1','form1',true)" />
</form>
<div id="txtHint"></div>
tags: