第一种方法
var bdkeyword = ""; $(".indexSearch input").keyup(function (e) { if (e.keyCode == 13) { window.open($(".indexSearch .btn").attr("href"), "_blank"); } else { $(".indexSearch .btn").attr("href", "https://www.baidu.com/s?ie=utf-8&wd=" + $(this).val()); } }); var keyword = ""; $(".indexSearch input").bind("input", function (e) { var that = $(this); if (keyword != that.val()) { var text = that.val(); $.ajax({ url: "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=" + text + "&cb=getvalue", dataType: "jsonp", type: "post", jsonp: "cb", success: function (data) { if (data) { laytpl($("#keywordList").html()).render(data, function (html) { if (html.trim() != "") { $(".selectul").show().html(html); } else { $(".selectul").hide().html(""); } }); } }, error: function (err) { } }); } });
直接调用百度接口然后输出数据到
<script id="keywordList" type="text/html"> {{#layui.each(d.s, function(index, item){}} <li> <a href="/go/?url=https://www.baidu.com/s?ie=utf-8&wd={{item}}" class="target" rel="external nofollow" target="_blank">{{item}}</a> </li> {{#})}} </script>
第二种是自己写一个api接口 PHP代码如下
<?php $word=$_GET["wd"]; $html = getArray($word); $res = getHtmlByContent($html); $result = array('p'=>'false','q'=>$word,'s' =>$res); echo json_encode($result); /** * getHtmlByContent * * @param mixed $html * @access public * @return void */ function getHtmlByContent($html){ preg_match_all('/<table cellpadding="0">.*<\/table>/',$html,$res); // print_r($res[0][0]); preg_match_all('/<th>.*?<\/th>/',$res[0][0],$result); $result = $result[0]; if(!empty($result) && is_array($result)){ foreach($result as $k=>$v){ $result[$k] = strip_tags($v); } } //print_r($result); return $result; } /** * getArray * * @param mixed $kw * @access public * @return void */ function getArray($kw){ $url="http://www.baidu.com/s?wd=".$kw; $curl=curl_init(); curl_setopt($curl,CURLOPT_URL,$url); curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); //curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost); $data = curl_exec($curl); $data = preg_replace("/[\r\n\t]+/","",$data); return $data; }
服务器配置差的情况下 方法1明显快于方法二