百度词条填充

来源:互联网 发布:nba2kol王朝软件 编辑:程序博客网 时间:2024/05/22 01:57

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)//obj是用this传递过来的当前点击对象
{
 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 = "#CCC";
 }

 

baibu.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){
 //var str = document.getElementById("search_text").value;
 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:#CCC; border:dashed #666 1px" id="div"></div></td></tr>
</table>
</center>
</body>
</html>

baidu.php文件

 

<?php
$jsonStr = "";
$link = mysql_connect('localhost','root','') or die("数据库连接失败");
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].'"},';//构造json为数组字面量,其中每一个元素为一个json格式的对象字面量
 }
$jsonStr=rtrim($jsonStr,',');//去除最右面的逗号
$jsonStr="[".$jsonStr."]";
echo $jsonStr;}//以数组字面量的形式将responseText返回
//需要将回传的数据用json表示(为了一行一行的遍历回传数据)
//对象字面量var obj = {属性名:属性值,...};
//数组字面量var arr =[值1,值2,...];//值可以为任意类型的数据
?>

 

 

 

 

 

原创粉丝点击