目的:
通过实验熟练掌握使用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;
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").click(function() {
var $tel = $("#tel").val();
$.ajax({
method: "GET",
url: "http://www.meishihui68.com.cn/api/tel?",
dataType: "json",
timeout: 3000,
data: {
tel: $tel
},
success: function(res) {
$("#address").html(res.result.mobilearea);
$("#yys").html(res.result.mobiletype);
},
error: function(xhr,e) {
alert("错误");
}
});
});
</script>