jQuery之AJAX
- 日常开发里为了提高开发效率,一般会使用框架中的AJAX语法,例如经常使用的jQuery,也给我们封装好了AJAX的一些语法操作,而且jQuery也封装了JSONP跨域。
- 几种常用的方式.ajax,.ajax,.ajax,.post, $.get, $.getJSON
- 1、$.ajax
- $.ajax是JQuery对ajax封装的最基础,通过使用这个函数可以完成异步通讯的所有功能。也就是说什么情况下都可以通过此方法进行异步刷新的操作。但是它的参数较多,有的时候可能会麻烦一些。
- 看一下常用的参数:
- type—数据的提交方式:get和post
- url—数据的提交路径 async—是否支持异步刷新,默认是true异步
data—参数值,需要提交的数据
dataType—服务器返回数据类型,例如xml,String,Json,jsonp等
beforeSend—请求前的回调函数、success—请求成功后的回调函数
error—请求失败后的回调函数、complete请求完成的回调函数(不论成功失败) - 2、$.post
- .post是对.post是对.post是对.ajax进行了更进一步的封装,减少了参数,简化了操作,但是运用的范围更小了。$.post简化了数据提交方式,只能采用POST方式提交。只能是异步访问服务器,不能同步访问,不能进行错误处理。
- 在满足这些情况下,可以使用这个函数来方便我们的编程,它的主要几个参数,像method,async等进行了默认设置,不可以改变。
jQuery之.get与.get与.get与.getJSON
- 3、$.get
- 和$.post一样,这个函数是对get方法的提交数据进行封装,只能使用在get提交数据解决异步刷新的方式上,使用方式和上边的也差不多。
- 4、$.getJSON
- 这个是进一步的封装,也就是对返回数据类型为Json进行操作。里边就三个参数,需要我们设置,非常简单:url,[data],[callback]
jQuery之$.ajax同源
- 【前言】
- 日常开发里,一般使用$.ajax即可实现所有操作,接下来结合案例讲解下
- 接下来分别介绍下利用$.ajax实现同源和跨域请求
- (1)$.ajax()方法实现同源数据请求
- (2)$.ajax()方法实现跨域数据请求
- (1)$.ajax()方法实现同源数据请求
- 请求完毕后再对返回数据进行解析,然后更新至HTML模板即可实现局部更新页面
- 接下来结合之前的JSONP跨域实现百度搜索关键字案例,这里利用jQuery的AJAX实现
- (2)$.ajax()方法实现跨域数据请求
- (2)$.ajax()方法实现跨域数据请求
- 其他设置和之前一样,直接修改js部分即可,如下所示
- (2)$.ajax()方法实现跨域数据请求注意事项
- 使用jQuery获取跨域数据
- 1、dataType:“jsonp”
- 2、jsonp默认值"callback",可以自行修改
jQuery之$.ajax参数
-
常用参数:
-
1、url
类型:String
默认值: 当前页地址。发送请求的地址。 -
2、type
类型:String
默认值: “GET”。请求方式POST或GET, 默认为 GET。注意:其它 HTTP 请求方法,如 DELETE 也可以使用,但仅部分浏览器支持。 -
3、async
类型:Boolean
默认值: true。默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。 -
注意:同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。 这里需要注意就是如果后面需要使用方法请求成功的数据,必须要设为同步,否则将会出现意想不到的错误,这个往往在刚开始使用ajax都会犯这个错误需特别留意
-
4、data
类型:String
发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。 -
5、jsonp
要求为String类型的参数,在一个jsonp请求中重写回调函数的名字。该值用来替代在”callback=?”这种GET或POST请求中URL参数里的”callback”部分 -
6、dataType
类型:String
预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断,比如 XML MIME 类型就被识别为 XML。在 1.4 中,JSON 就会生成一个 JavaScript 对象,而 script 则会执行这个脚本。随后服务器端返回的数据会根据这个值解析后,传递给回调函数。 -
6、dataType可用值:
“xml”: 返回 XML 文档,可用 jQuery 处理。
“html”: 返回纯文本 HTML 信息;包含的 script 标签在插入 dom 时执行。
“script”: 返回纯文本 JavaScript 代码。不会自动缓存结果。除非设置了 “cache” 参数。注意:在远程请求时(不在同一个域下),所有 POST 请求都将转为 GET 请求。(因为将使用 DOM 的 script标签来加载) -
6、dataType可用值:
“json”: 返回 JSON 数据 。
“jsonp”: JSONP 格式。使用 JSONP 形式调用函数时,如
“callback=?” jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。
“text”: 返回纯文本字符串 -
7、success
要求为Function类型的参数,请求成功后调用的回调函数 -
8、error
要求为Function类型的参数,请求失败时被调用的函数 -
9、beforeSend
要求为Function类型的参数,发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义HTTP头。在beforeSend中如果返回false可以取消本次ajax请求。 -
10、complete
要求为Function类型的参数,请求完成后调用的回调函数(请求成功或失败时均调用)。参数:XMLHttpRequest对象和一个描述成功请求类型的字符串。 -
11、jsonp
请求自动带上callback参数,callback值为jsonpCallback的值 -
12、jsonpCallback
JSONP回调函数callback的值
jQuery之AJAX案例
- 案例:天气查询
- 案例:天气查询—【前言】
聚合数据全国天气预报接口:https://www.juhe.cn/docs/api/id/39
- 点击链接注册并获取KEY密钥,选择天气预报接口,可以免费调用500次
- 案例:天气查询—逻辑梳理
1、输入城市名
2、点击的时候发送请求
3、响应成功渲染页面 - 案例:天气查询,部分实现代码(静态)
- 案例:天气查询,部分实现代码(逻辑)
- 接下来对上述做下完善修改,如下所示
- 1、将url中的参数放到data选项里,参数如下
2、添加jsonp和jsonpCallback选项 - 完整代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jq-3.3.1.js"></script>
<style>
*{
margin: 0;
padding: 0;
}
.da{
width: 800px;
height: 500px;
margin: 50px auto 0;
background: url(img/bjt.jpg) no-repeat;
background-size: 100% 100%;
border-radius: 50px;
}
.zhezhao{
width: 800px;
height: 500px;
background: rgba(00,00,00,.3);
border-radius: 50px;
}
.box_one{
width: 100%;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
}
.box_one input{
width: 500px;
height: 40px;
outline: none;
border: none;
box-sizing: border-box;
padding-left: 30px;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
font-size: 18px;
/* background: rgba(255,255,255,.3); */
/* color: white; */
}
.box_one button{
width: 80px;
height: 42px;
outline: none;
}
#box_two{
width: 80%;
height: 100px;
background: rgba(255,255,255,.5);
margin: 0 auto;
border-radius: 20px;
box-sizing: border-box;
}
p{
color: white;
font-size: 18px;
padding: 10px 20px;
}
</style>
</head>
<body>
<div class="da">
<div class="zhezhao">
<div class="box_one">
<input id="ipt" type="phone" placeholder="请输入您要查询的城市">
<button class="btn">查询</button>
</div>
<div id="box_two"></div>
<div id="box_three"></div>
</div>
</div>
</body>
<script type="text/javascript">
function callback_fn() {
/*
* 成功执行时的回调,可以在外部执行
* 作用域success成功回调一样
* 开发一般使用success即可
*/
}
$(function() {
$(".btn").on('click',function(){
var city = $('#ipt').val() || '石家庄';
$.ajax({
type:"get",
url:'http://v.juhe.cn/weather/index',
data:{
"format":2,
"cityname":city,
"key": '03373911bab25d1179cff10ca48f23e1'
},
async:true,
dataType:"jsonp",
jsonp:"callback",
/*请求自动带上callback参数,callback值为jsonpCallback的值*/
jsonpCallback:'callback_fn',
success(data){
if (data.resultcode == 200) {
var sk = data.result.sk;
var today = data.result.today;
var futur = data.result.future;
var info = "";
info +="<p>";
info += today.city + " " + " " +
today.week + " " + " " +
"当日温度:" + sk.temp + "℃" + " " + " " +
"当日风向:" + sk.wind_direction + " " + " " +
"当日风力:" + sk.wind_strength + " " + " " +
"温湿度:" +sk.humidity + " " + " " +
"当日时间:" + sk.time + " " + " " +
"当日温度:" + today.temperature + " " + " " +
today.date_y + " " + " "
info +="<p>"
$("#box_two").html(info)
$('#ipt').val("")
} else{
alert(data.reason)
}
var two = ""
for (var i = 0; i < futur.length; i++) {
two +="<p>"
two += futur[i].week + " " + " " +
futur[i].temperature + " " + " " +
futur[i].weather + " " + " " +
futur[i].wind + "   " + " " +
futur[i].date + "  "
two +="</p>"
$("#box_three").html(two)
}
},
error() {
alert('error')
}
});
})
})
</script>
</html>
jQuery之AJAX作业
- JSON API免费线上接口
- http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=手机号
- 要求
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jq-3.3.1.js"></script>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.box {
width: 800px;
height: 500px;
background: rgba(00, 00, 00, .5);
margin: 0 auto;
}
.box_one {
width: 800px;
height: 100px;
border: 1px solid red;
margin: 0 auto;
display: flex;
justify-content: center;
align-items: center;
}
input {
width: 400px;
height: 40px;
font-size: 18px;
outline: none;
/* border: none; */
}
button {
width: 80px;
height: 44px;
outline: none;
}
.bottom {
width: 800px;
height: 400px;
border: 1px solid red;
/* display: flex; */
padding: 150px 300px;
/* align-items: center; */
box-sizing: border-box;
position: relative;
/* justify-content: center; */
}
#loadingImg {
position: absolute;
margin: auto;
left: 0;
top: 0;
right: 0;
bottom: 0;
display: none;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="box">
<div class="box_one">
<input type="tel" placeholder="请输入您要查询的手机号" />
<button id="btn">查询</button>
</div>
<div class="bottom">
<img src="img/loading.gif" id="loadingImg">
</div>
</div>
</body>
<script type="text/javascript">
function callbackFN(option) {
console.log('自定义成功')
console.log(option)
}
$(function() {
$(document).ajaxStart(function(event, request, settings) {
/* $( "#loadingImg" ).css("display","block"); */
$(".bottom").html('<img src="./img/loading1.gif" id="loadingImg" style="display:block;">');
});
$(document).ajaxSuccess(function(event, request, settings) {
$("#loadingImg").css("display", "none");
});
$("#btn").click(function() {
let tel = $('input[type="tel"]').val();
$.ajax({
url: "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm",
type: 'get',
data: {
'tel': tel
},
async: true,
dataType: 'jsonp',
jsonpCallback: 'callbackFn',
success: function(res) {
console.log('成功')
console.log(res)
let showHtml = "";
showHtml += "<h4>一级归属:" + res.catName + "</h4>";
showHtml += "<h4>二级归属:" + res.carrier + "</h4>";
showHtml += "<h4>归属地:" + res.province + "</h4>";
showHtml += "<h4>手机号:" + res.telString + "</h4>";
$(".bottom").html(showHtml);
},
error: function(err) {
console.log(err)
}
});
tel = $('input[type="tel"]').val("");
})
var input = document.getElementsByTagName("input")[0];
var zz = /^1(3|4|5|7|8)\d{9}$/;
input.onblur = function() {
if (zz.test(input.value)) {
} else {
alert("请输入正确的手机号")
tel = $('input[type="tel"]').val("");
}
};
})
</script>
</html>
API接口
- 拓展:
- 提供JSON格式数据返回服务网站的API接口,为大家搜集了一些能够返回JSON格式的服务接口。部分需要用JSONP调用
- 链接:http://www.bejson.com/knownjson/webInterface/
全局事件处理程序
- 这里补充介绍下全局Ajax事件处理程序
- 详情参见jquery的AJAX官方API文档
链接:https://api.jquery.com/category/ajax/global-ajax-event-handlers/
案例及API调用实例(注意版本1.9+):