百度搜索效果(页面传来数据地址,由服务器去获取):
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>页面传来数据地址,由服务器去获取</title> <style type="text/css"> * { margin: 0; padding: 0; list-style: none; } #box { 500px; margin: 50px auto 0; } #ipt { 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="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('baidu2.php?wd='+ipt.value+'&sc=http://suggestion.baidu.com/su?wd=&_='+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=';//由服务器来获取数据 $url=$_GET['sc'];//页面传过来数据地址,由服务器去获取 function getJSONStr($str){ return substr($str,17); } function crul($key){ global $url; $data = file_get_contents($url.$key); $data = getJSONStr($data); $data = str_replace("{q:"","",$data); $data = str_replace("",p:","{%aaa%}",$data); $data = str_replace(",s:[","{%aaa%}",$data); $data = 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); ?>