标签:
随便写了个jsonp模拟百度搜索相关词汇的小demo,帮助新手理解jsonp的用法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模拟百度搜索框</title>
<style>
*{
margin: 0;
padding: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
ul,li{
list-style: none;
}
.baiduSearch{
width: 600px;
margin:100px auto 0;
text-align: center;
}
#search_txt{
width: 500px;
height: 40px;
border:1px solid #ccc;
border-right: 0;
outline: 0;
text-indent: 10px;
font-size: 24px;
}
#search_btn{
display: inline-block;
width: 100px;
height: 40px;
line-height: 40px;
vertical-align: top;
font-size: 20px;
cursor: pointer;
color:#666;
border:1px solid #ccc;
text-decoration: none;
}
.result{
width: 500px;
border:1px solid #ccc;
border-top: 0;
display: none;
}
.result>li{
height: 30px;
line-height: 30px;
text-align: left;
text-indent: 10px;
}
</style>
</head>
<body>
<div class="baiduSearch">
<input type="text" id="search_txt"><a href="javascript:;" id="search_btn">搜索</a>
<ul class="result"></ul>
</div>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script>
$("#search_txt").on("keydown",function(){
$("#search_btn").attr("href","https://www.baidu.com/s?wd="+$("#search_txt").val());
$(".result>li").remove();
if($(".result>li").length==0){
$(".result").hide();
}
$.ajax({
type:"get",
url:"https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su",
data:{wd:$(this).val()},
dataType:"jsonp",
jsonp:"cb",
success:function(data){
for(var i = 0;i<data.s.length;i++){
var oLi=$("<li>"+data.s[i]+"</li>");
$(".result").show().append(oLi);
}
}
});
});
</script>
</body>
</html>
演示地址: jsonp搜索
标签:
原文地址:http://www.cnblogs.com/raoyunxiao/p/4761682.html