img

使用jQuery来发送 AJAX 请求会比较方便


使用jQuery 发送get和post请求

get和post请求有四个参数:

$.get(url,[data],[callback],[type])

  url:请求的 URL 地址。

  data:请求携带的参数。

  callback:载入成功时回调函数。

  type:设置返回内容格式,xml,html,script,json,text,_default。

1
2
3
4
5
6
7
8
9
10
11
12
13
      //发送get请求
$('button').eq(0).click(function(){
$.get('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){
console.log(data);
},'json');
});

//发送post请求
$('button').eq(1).click(function(){
$.post('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){
console.log(data);
});
});

jQuery通用方法发送AJAX请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$('button').eq(2).click(function(){
$.ajax({ //-------------------------------------
//url
url: 'http://127.0.0.1:8000/jquery-server',
//参数
data: {a:100, b:200},
//请求类型
type: 'GET',
//响应体结果
dataType: 'json',
//成功的回调
success: function(data){
console.log(data);
},
//超时时间
timeout: 2000,
//失败的回调
error: function(){
console.log('出错啦!!');
},
//头信息
headers: {
c:300,
d:400
}
});

其他的参数:—–传送门—–

总结:

我们平常使用的话,get和post请求就完全够用了,如果想要个性化的去请求数据,可以使用jQuery通用方法 $.ajax()