仿百度词条搜索功能代码

来源:互联网 发布:太空漂浮舱骗局知乎 编辑:程序博客网 时间:2024/05/16 16:02

baidu.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script language="javascript" type="text/javascript" src="noAjax.js">
</script>
<script language="javascript" type="text/javascript" src="ajax.js">
</script>
<script language="javascript" type="text/javascript">
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;
}
</script>
</head>
<body onload="initBaidu()">
<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="position:relative; background-color:#FFF"; border:dashed #666 1px; id="div">
</div></td></tr>
</table>
</center>
</body>

</html>


baidu.php

<?php
$jsonStr = "";
$link = mysql_connect('localhost','root','');
mysql_select_db('baidu',$link);
mysql_query('set names utf8');
if($_GET["c"]!=''){
$result = mysql_query("select content from c where content like'".$_GET["c"]."%'");
while($row = mysql_fetch_row($result)){
$jsonStr.='{text:"'.$row[0].'"},';
}
$jsonStr=rtrim($jsonStr,',');
$jsonStr="[".$jsonStr."]";
echo $jsonStr;}
?>


ajax.js

function initXHR(){
return window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
}
function testXHR(serverUrl,Parms,callBack){
var xhr = initXHR();//初始化XHR
var url = serverUrl+"?"+Parms+"&r="+Math.random();//初始化url
xhr.open("GET",url,true);//打开url
xhr.send(null);//发送请求
xhr.onreadystatechange = function(){
if(xhr.readyState==4) {
callBack(xhr);
}
}
}

noAjax.js

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="#FFF";
}// JavaScript Document

原创粉丝点击