https://www.w3school.com.cn/jquery/jquery_ref_ajax.asp
jq中
jQuery中用来发ajax请求的方法,跟我们封装的方法类似,但是功能更强大
//传入一个对象
$.ajax({
//请求网址
url: './data.php',
//请求类型
type: 'post',
//服务器响应数据类型,如果是跨域,可以改成jsonp
dataType: 'json',
//发送给服务器的数据(请求体),如果是get请求数据写在url,如果是post才写data属性
data: { id: 1 },
//回调函数:响应回来调用的函数
success: function (data) {
console.log(data)
},
//请求失败触发
error: function (err) {
console.log(err)
}
})
$.get
专门用来只做 get
请求的方法,参数与 ajax
方法一样,只是不用写 type
$.get({
url:'http://api.douban.com/v2/movie/top250',
dataType:'jsonp',
success:function(data){
console.log(data);
}
})
或者可以不传对象,传四个参数
$.get('http://api.douban.com/v2/movie/top250',function(data){
console.log('data');
},'jsonp')
$.post
专门用来只做 post
请求的方法,参数与 ajax
方法一样,只是不用写 type
$.post({
url:'./data.php',
//传字符串
data:"name=jack&pwd=123",
success:function(data){
console.log(data);
}
})
或者可以不传对象,传四个参数
$.get('http://api.douban.com/v2/movie/top250',
{name:"jack", pwd:123},
function(data){
console.log('data');
},
'jsonp');
封装
封装ajax代码之一
/**
* type: 请求方式
* url:请求路径
* data:发送请求时提交的数据 都要传 key=value的形式
*/
// 三.1 加了一个形参success
function ajax(type, url, data, success) {
//把相同的代码封装起来
//1. 创建请求对象
var xhr = new XMLHttpRequest();
//二.1 如果有传数据过来,并且是get请求,应该拼接网址了
if (data != "" && type.toLocaleLowerCase() == 'get') {
url += "?" + data;
}
//2. 设置请求行(用传进来的参数来填充)
xhr.open(type, url);
//二.2 如果是post请求还要设置请求头
if (type.toLocaleLowerCase() == "post") {
//设置请求头
xhr.setRequestHeader('Content-type', "application/x-www-form-urlencoded");
//3. 发送请求
xhr.send(data); //如果是POST请求,把数据直接send过去
} else {
xhr.send(); //如果是get就发空参数
}
//4. 监听响应完成事件