When j is entered, the ajax effect will be triggered, the corresponding data with j in the name will be obtained from the background, and displayed in suggestions.
The code is implemented as follows:
Three files are required to implement ajax, one is the html form file, one is the js core file, and the other is the php background file.
The following is an html file. The showHint method is triggered when the keyboard is pressed. In the showHint method, there will be the core content of ajax, instantiation, obtaining the address, obtaining data and displaying it, etc.
The following is the content of js clienthint.js.
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML=""
return
}
//Get the xmlHttpObject object. If it is empty, it prompts that the browser does not support ajax
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
//Get url
var url="gethint.php"
url=url+"?q="+str
url =url+"&sid="+Math.random()
//Callback function, perform action
xmlHttp.onreadystatechange=stateChanged
//open
xmlHttp.open("GET",url,true )
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
//Insert the obtained information into txtHint
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}
//Get xml object
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;
}
The following is the content of php. Get the corresponding data based on the parameters passed in by the ajax object.
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i =0; $i
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)) ))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
//Set output to "no suggestion" if no hint were found
//or to the correct values
if ($hint == "")
{
$response=" no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>