首页 > 代码库 > 百度搜索效果(服务器来获取数据)

百度搜索效果(服务器来获取数据)

百度搜索效果:

AJAX代码:

ajax本身不具有跨域功能,所以由服务器来访问数据:

<!DOCTYPE html><html>	<head>		<meta charset="UTF-8">		<title>由服务器来获取数据</title>		<style type="text/css">			* {				margin: 0;				padding: 0;				list-style: none;			}			#box {				width: 500px;				margin: 50px auto 0;			}			#ipt {				width: 480px;				height: 30px;				padding: 0 8px;				line-height: 30px;				font-size: 18px;			}			#list {				padding: 0 10px;				background: #e3e3e3;			}			#list li {				line-height: 26px;				font-size: 16px;				color: blue;			}			#list li:hover {				background: #ccc;			}		</style>	</head>	<body>		<div id="box">			<input type="text" name="ipt" id="ipt" value="" />			<ul id="list">				<!--<li>12306</li>				<li>hao123</li>-->			</ul>		</div>		<script src="http://www.mamicode.com/ajax.js" type="text/javascript" charset="utf-8"></script>		<script type="text/javascript">			var ipt = document.getElementById(‘ipt‘);			var list = document.getElementById(‘list‘);			ipt.onkeyup = function() {				list.innerHTML = ‘‘;				ajax(‘baidu.php?wd=‘+ipt.value+‘&_=‘+new Date().getTime(),function(str) {					var json = JSON.parse(str);					for(var i = 0; i < json.s.length; i ++) {						list.innerHTML += ‘<li>‘+json.s[i]+‘</li>‘;					}				});				/*ajax(‘baidu.php?wd=‘+ipt.value+‘&t=‘+new Date().getTime(),function (str){					var json=JSON.parse(str);					for (var i = 0; i < json.s.length; i++) {						list.innerHTML+=‘<li>‘+json.s[i]+‘</li>‘;					};				});*/			}		</script>	</body></html>

  PHP代码:

<?php	header("Access-Control-Allow-Origin:*");	$url=‘http://suggestion.baidu.com/su?wd=‘;//由服务器来获取数据	function getJSONStr($str){		return substr($str,17);	}	function crul($key){		global $url;		$data = http://www.mamicode.com/file_get_contents($url.$key);"{q:\"","",$data);		$data = http://www.mamicode.com/str_replace("\",p:","{%aaa%}",$data);		$data = http://www.mamicode.com/str_replace(",s:[","{%aaa%}",$data);		$data = http://www.mamicode.com/str_replace("]});","",$data);		$arr = explode("{%aaa%}",$data);		$res = array();		$res[‘q‘] = iconv("GB2312","UTF-8",$arr[0]);		if ($arr[1] == ‘true‘){			$arr[1] = true;		}else{			$arr[1] = false;		}		$res[‘p‘] = $arr[1];		if (strlen($arr[2])>0){			$arr[2] = substr($arr[2],1,-1);			$arr[2] = str_replace("\",\"",",",$arr[2]);			$arr[2] = iconv("GB2312","UTF-8",$arr[2]);		}				$res[‘s‘] = explode(‘,‘,$arr[2]);		echo json_encode($res);//json_encode()转换成json字符串	}	$key = $_REQUEST[‘wd‘];	crul($key);?>

  

百度搜索效果(服务器来获取数据)