使用jQuery的ajax的方法完成一个手机归属地查询
1.设计页面的效果;
2. 选用HTTP GET方法,将电话提交到服务端,并将返回的结果显示在界面相应的位置;
3. 服务端API地址:http://www.meishihui68.com.cn/api/tel;
4. 数据提交方法:
需要在API地址后面以“?”方式附加,例如
http://www.meishihui68.com.cn/api/tel? tel=13021671512。
style样式代码:
<style>
#mydiv {
height: 230px;
width: 300px;
background-color: #e8f7f2;
margin: auto;
text-align: center;
}
#div1 {
background-color: #22be81;
text-align: center;
line-height: 50px;
}
.tel {
margin-top: 15px;
border: 0.5px solid gainsboro;
border-radius: 5px;
height: 30px;
width: 250px;
text-align: center;
}
.search {
margin-top: 20px;
border: 0.5px solid gainsboro;
border-radius: 5px;
height: 28px;
width: 250px;
text-align: center;
background-color: #ff767a;
color: white;
}
#div2 {
height: 50px;
width: 275px;
background-color: white;
margin: 10px;
text-align: left;
font-size: 10px;
padding: 7px 0px 0px 5px;
}
</style>
主体部分代码:
<body>
<div id="mydiv">
<div id="div1">手机归属地查询</div>
<input type="text" placeholder="电话:请输入手机号码" class="tel" />
<input type="submit" value="查询" class="search" />
<div id="div2">
<div>号码归属地:<span id="address"></span></div><br />
<div>提供商:<span id="provider"></span></div>
</div>
</div>
<script src="js/jquery-2.1.0.js"></script>
<script>
$('.search').click(function() {//为查询按钮实现事件监听
var $tel = $(".tel").val();//定义一个JQuery对象,筛选出电话输入框,用于提取用户输入的电话号码
$.ajax({
method: "GET",//get方法
datatype: "json",
url: "http://www.meishihui68.com.cn/api/tel?",//API地址
timeout: 2000,//设置超时事件为2s
data: {
tel: $tel
},
success: function(res) {
$('#address').html(res.result.mobilearea);//处理json对象res,从返回值中筛选出所需的值
$('#provider').html(res.result.mobiletype);
},
error: function() {
alert("错误");
}
});
});
</script>
</body>