ajax百度词条

来源:互联网 发布:windows核心编程 源码 编辑:程序博客网 时间:2024/05/17 22:23

1先创建了一个“百度一下,你就知道”的页面
<center>
<h1>百度一下,你就知道</h1><br />
<table><tr><td>
<form action="" method="post">
<input type="text" size="30" id="search_text"  onkeyup="testAjax(this.value)"/></td><td>
<input type="submit" value="点击查询" /></td>
</form></tr>
<tr><td>
<div style="background-color:#999; position:relative border:dashed #666 1px" id="div">
</div></td></tr>
</table>
</center>
2创建数据库,连接数据库,用$_GET["c"]取出一个值,利用json查找出与输入内容相关的内容,然后显示。
$link = mysql_connect('localhost','root','`123') or die ("数据库连接失败");
mysql_select_db('baidu',$link);
mysql_query('set names utf8');
if($_GET["c"]!=''){
$result = mysql_query("select content from c when content like '".$_GET["c"]."%'");
while($row = mysql_fetch_row($result)){
 $jsonStr.='{text:"'.$row[0].'"},';
 }
 $jsonStr=rtrim($jsonStr,',');
 $jsonStr="[".$jsonStr.']';
 echo $jsonStr;
}
3连入ajax异步通信模板,连接数据库内容,在div中显示待选内容。
function initBaidu(){
 document.getElementById("div").style.border="none";
 }
function testAjax(str){
 testXHR('baidu.php',"c="+encodeURI(str),m_xhr);
 }
function m_xhr(xhr){
 var str="";
 var json = eval("("+xhr.responseText+")");
 for(var i=0;i<json.length;i++)
 str += '<span style="position:absolute; left:0" onclick="chooseIt(this)" onmouseover="onIt(this)" onmouseout="outIt(this)">'+json[i].text+'</span><br />';
 document.getElementById("div").innerHTML=str;
 }
4利用函数实现鼠标移动到指定一行内容变色,鼠标移走变回原色。
function chooseIt(obj){
 document.getElementById("search_text").value = obj.innerHTML;
 document.getElementById("div").innerHTML = "";
 document.getElementById("div").style.border = "none";
 }
function onIt(obj){
 obj.style.backgroundColor ="#36F";
 }
function outIt(obj){
 obj.style.backgroundColor ="#999";
 } 

原创粉丝点击