目的:
通过实验熟练掌握使用AJAX通信。
要求:
- 掌握AJAX通信的基本原理;
- 掌握XMLHttpRequest对象的使用;
- 掌握jQuery的ajax请求方法;
实验步骤(及实验数据)
内容:
使用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
界面代码
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#mydiv {
width: 300px;
height: 220px;
margin: auto;
text-align: center;
/*也支持子div的居中*/
background-color: #e8f7f2;
}
input {
border-radius: 5px;
border: 1px solid gainsboro;
line-height: 40px;
width: 75%;
text-align: center;
font-size: 15px;
}
.result {
width: auto;
line-height: 20px;
background-color: white;
padding: 3px;
}
span {
text-align: left;
font-size: 10px;
}
</style>
</head>
<body>
<div id="mydiv">
<div style="background-color: #22be81; line-height: 40px;">手机归属地查询</div>
<input type="text" id="tel" style="margin-top: 12px;" placeholder="电话:请输入手机号码" />
<input type="submit" id="Search" value="查询" style="background-color: #ff767a; margin-top: 15px; color: white;line-height: 25px;" />
<div class="result" style=" margin: 10px;">
<div class="result" style="text-align: left; font-size: 10px;">号码归属地:<span id="address"></span></div>
<div class="result" style="text-align: left; font-size: 10px;">提供商:<span id="yys"></span></div>
</div>
</div>
</body>
</html>
script关键代码
<script src="js/jquery-2.1.0.js"></script>
<script>
//实现按钮事件监听 Search指查询按钮
$("#Search").click(function() {
//筛选出电话输入框,用于提取用户输入的电话号码
//#tel 指电话号码的输入框
var $tel = $("#tel").val();
//运用JQuery的ajax方法
$.ajax({
//请求方法
method: "GET",
//请求地址
url: "http://www.meishihui68.com.cn/api/tel?",
//预期放回的数据类型
dataType: "json",
//设置请求超时时间
timeout: 3000,
//发送的数据
data: {
tel: $tel
},
success: function(res) {
//处理Json对象res
//将所需值打印到界面
$("#address").html(res.result.mobilearea);
$("#yys").html(res.result.mobiletype);
},
error: function(xhr,e) {
//处理错误信息
alert("错误");
}
});
});
</script>