1. 程式人生 > >js 模糊查詢 (360介面)

js 模糊查詢 (360介面)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
	</head>
	<body>
		<style>
			*{margin:0;padding: 0;}
			.text{position: relative;}
			.text input{width:200px;height: 35px;line-height: 35px;padding-left: 10px;border:2px solid #0095ea;border-radius: 3px;position: relative;z-index: 2;;}
			.text ul{position: absolute;top: 38px;left: 0;border: 1px solid #abb9c1;display: none;background: #fff;z-index: 1;}
			
			.text ul li{height: 25px;min-width:192px; line-height: 25px;padding:0 10px;list-style: none;cursor: pointer;font-size: 12px;}
			.text ul li:hover{background: #ccc;}
		</style>
		<div class="text">
			<input type="text" />
			<ul></ul>
		</div>
		<script>
			window.onload=function(){
				var tel;
				$(".text input").bind('input propertychange',function(){
					
					tel=$(this).val();
					
					console.log(tel)
					$(this).siblings("ul").show();
					$(this).siblings("ul").html(''); 
					$.ajax({
					    type:"get",    //請求方式
					    async:true,    //是否非同步 
					   url:"https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word="+tel, //360介面
					    dataType:"jsonp",    //跨域json請求一定是jsonp
					    jsonp: "callback",    //跨域請求的引數名,預設是callback
					    jsonpCallback: "suggest_so",  //自定義跨域引數值,回撥函式名也是一樣,預設為jQuery自動生成的字串
					    //jsonpCallback:"successCallback",    //自定義跨域引數值,回撥函式名也是一樣,預設為jQuery自動生成的字串
					   
					
					    beforeSend: function() {
					    	console.log(1)
					        //請求前的處理
					    },
					
					    success: function(data) { 
							var _html='';
					    	for(var i=0;i<data.result.length;i++){
					    		_html +='<li>'+data.result[i].word+'</li>';
					    	}
					    	$(".text ul").html(_html)
					        //請求成功處理,和本地回撥完全一樣
					    },
					
					    complete: function() {
					    	console.log(2)
					        //請求完成的處理
					    },
					
					    error: function() {
					        //請求出錯處理
					        console.log(3)
					    }
					});
					
				});
				
				$(".text").on('click','ul li',function(){
					$(this).parent().siblings('input[type=text]').val($(this).text());
					$(this).parent().hide();
				})
			
			}
		</script>
	</body>
</html>