最好的网站制作公司seo和sem
Get请求
语法格式:
$.get(url, [data], [callback], [type])
url: | 请求的 URL 地址。 |
data: | 请求携带的参数。 |
callback: | 载入成功时回调函数。 |
type: | 设置返回内容格式,xml, html, script, json, text, _default。 |
准备三个按钮分别测试Get 、Post、通用型方法
<div class="container"><h2 class="page-header">jQuery发送AJAX请求 </h2><button class="btn btn-primary">GET</button><button class="btn btn-danger">POST</button><button class="btn btn-info">通用型方法ajax</button></div>
1. JS
//第一个参数:URL,第二个参数:传递参数,对象(key-value格式),第三个参数:回调 第四个参数:返回数据格式$('button').eq(0).click(function(){$.get('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){console.log(data);},'json'); //返回对象});
2. 服务
//jQuery 服务
app.all('/jquery-server', (request, response) => {//设置响应头 设置允许跨域response.setHeader('Access-Control-Allow-Origin', '*');response.setHeader('Access-Control-Allow-Headers', '*');const data = {name:'德仔'};response.send(JSON.stringify(data));
});
返回是对象格式
Post请求
url: | 请求的 URL 地址。 |
data: | 请求携带的参数。 |
callback: | 载入成功时回调函数。 |
type: | 设置返回内容格式,xml, html, script, json, text, _default。 |
1. js
$('button').eq(1).click(function(){$.post('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){console.log(data);}); //返回字符串});
2. 服务同Get
第四个参数:返回数据格式区别
Get请求添加参数’json’,Post 请求未添加
通用型方法
JS
$('button').eq(2).click(function(){$.ajax({//urlurl: '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}});});