目录
AJAX
原生ajax发送get请求
前端代码
<button>点击发送请求</button>
<div id="result">
</div>
<script>
// 绑定按钮
const bt = document.getElementsByTagName('button')[0];
const result = document.getElementById('result');
bt.onclick = function () {
//1.创建异步对象
const xhr = new XMLHttpRequest();
//2.初始化,设置请求方法和url(通过?的方式可以添加参数)
xhr.open('GET', "http://localhost:8080/server?a=100&b=200");
//3.发送
xhr.send();
//4.事件绑定 处理服务端返回的结果
//readystate 是xhr对象的属性,表示状态 0,1,2,3,4
//change 改变时触发
xhr.onreadystatechange = function () {
//5. 判断,只有状态为4时处理(返回了所有结果)
if (xhr.readyState == 4) {
//6. 判断响应状态码
if (xhr.status >= 200 && xhr.status <= 300){
//7.处理结果 行,头,空行,体
//7.1 响应行
console.log(xhr.status); //响应状态码
console.log(xhr.statusText); //状态字符串
console.log(xhr.getAllResponseHeaders()); //响应头
console.log(xhr.response); //响应体
//8.显示结果
result.innerHTML = xhr.response;
}else {
}
}
};
};
</script>
后端请求接口
@RequestMapping("/server")
@ResponseBody
public String ajax() {
return "hello, I am your farther";
}
原生ajax发送post请求
前端代码
<div id="result">
</div>
<script>
//1.获取对象
const result = document.getElementById('result');
//2.绑定事件
result.addEventListener('mouseover',function () {
//1.创建异步对象
const xhr = new XMLHttpRequest();
//2.初始化,设置类型和url
xhr.open('POST','http://localhost:8080/server1');
//设置请求头,可不设置(请求体类型)
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//3.发送请求(可以传递参数)
xhr.send('a=10&b=100');
//4.处理响应
xhr.onreadystatechange = function () {
//1.判断状态码
if (xhr.readyState == 4){
//2.判断响应码
if (xhr.status >= 200 && xhr.status <= 300){
//3.处理返回结果
result.innerHTML = xhr.response;
}
}
}
})
</script>
后端响应接口
@RequestMapping("/server1")
@ResponseBody
public String ajaxPost(HttpServletResponse response) {
//设置响应头,允许跨域
response.setHeader( "Access-Control-Allow-Origin", "*" );
//设置响应头,允许访问的头参数
response.setHeader( "Access-Control-Allow-Header", "*" );
return "hello, I am Post";
}
原生ajax与json数据的交互
前端代码
<div id="result">
</div>
<script>
//1.绑定事件
window.onkeydown = function () {
const result = document.getElementById('result');
//2.新建异步请求
const xhr = new XMLHttpRequest();
//设置返回值类型,可以自动转换为json(也可以通过JSON.parse()手动转换)
xhr.responseType = 'json';
//3.初始请求(添加时间戳,解决ie缓存问题)
xhr.open('GET',"jsonServer")
//4.发送请求
xhr.send();
//5.处理返回值
//1.绑定状态更改事件
xhr.onreadystatechange = function () {
if (xhr.readyState==4){
if (xhr.status >= 200 && xhr.status <= 300){
//let i = JSON.parse(xhr.response);(手动转换json格式)
let i = xhr.response;
result.innerHTML = "name:"+i.name;
}
}
}
}
</script>
后端响应接口(需要导入JSON jar包)
@RequestMapping("/jsonServer")
@ResponseBody
public String jsonServer(HttpServletResponse response){
//设置响应头,允许跨域
response.setHeader( "Access-Control-Allow-Origin", "*" );
Map<String,Integer> map = new HashMap<>();
map.put("name", 12);
map.put("id", 1);
String json = JSON.toJSONString(map);
return json;
}
解决IE浏览器缓存问题
在IE浏览器当中,由于浏览器自身的缓存,会让后台接口的数据不可以实时的进行更新,可以使用加入时间戳的方式来解决这一问题,它会根据时间戳不同判断我们的每次请求都属于不一样的请求,从而实现数据的更新。
解决方法:
在url中加入时间戳参数
xhr.open('GET',"jsonServer?t="+Date.now())
ajax请求超时与网络异常处理
后端模拟请求超时环境
@RequestMapping("/request")
@ResponseBody
public String request() throws InterruptedException{
Thread.sleep(3000);
return "hello, I am your farther";
}
前端设置超时处理
<div id="result">
</div>
</body>
<script>
window.onkeydown = function () {
const result = document.getElementById('result');
const xhr = new XMLHttpRequest();
xhr.open('GET',"request")
//设置超时2秒自动取消
xhr.timeout = 2000
//设置超时回调
xhr.ontimeout = function(){
alert("请求异常");
}
//设置网络异常回调
xhr.onerror = function(){
alert("你的网络似乎有点问题,检查一下?");
}
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState==4){
if (xhr.status >= 200 && xhr.status <= 300){
result.innerHTML = xhr.response;
}
}
}
}
</script>
Ajax手动取消请求
前端代码
<button>发送请求</button>
<button>取消请求</button>
<div id="result"></div>
<script>
const btnS = document.getElementsByTagName('button');
const result = document.getElementById('result');
let xhr = null;
btnS[0].addEventListener('click',function () {
xhr = new XMLHttpRequest();
xhr.open('GET','stop');
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4){
if (xhr.status <= 300 && xhr.status >= 200){
result.innerHTML = xhr.response;
}
}
}
})
btnS[1].addEventListener('click',function () {
//取消提交
xhr.abort();
})
</script>
后端请求接口
@RequestMapping("/stop")
@ResponseBody
public String stop() throws InterruptedException {
//设置延时,给予反应事件
Thread.sleep(3000);
return "hello";
}
Ajax解决重复请求问题
为了避免一直重复的点击造成不必要的接口请求压力,对于某些数据不会轻易发生改变的值可以设置避免浏览器重复请求。比如说,我们加载某一不被更改的组件模块时。
前端代码
<button>发送请求</button>
<button>取消请求</button>
<div id="result"></div>
<script>
const btnS = document.getElementsByTagName('button');
const result = document.getElementById('result');
let xhr = null;
//加入标识,判断是否正在发送AJAX请求
let isSending = false;
btnS[0].addEventListener('click',function () {
//判断标识变量
if (isSending) xhr.abort(); //如果正在执行另一个xhr,取消另一个xhr
xhr = new XMLHttpRequest();
//请求开始,更改标识状态
isSending = true;
xhr.open('GET','stop');
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4){
//请求完成,更改状态码状态
isSending = false
if (xhr.status <= 300 && xhr.status >= 200){
result.innerHTML = xhr.response;
}
}
}
})
btnS[1].addEventListener('click',function () {
//取消提交
xhr.abort();
})
</script>
后端接口
@RequestMapping("/stop")
@ResponseBody
public String stop() throws InterruptedException {
//设置延时,给予反应事件
Thread.sleep(3000);
return "hello";
}
jQuery发送ajax请求
前端代码
<button>GET</button>
<button>POST</button>
<button>通用型方法ajax</button>
<div id="result">
</div>
<script>
$('button').eq(0).click(function () {
//1.设置请求方式, URl, 传递参数, 回调参数
$.get('jquery', {a:100, b:200}, function (data) {
$('#result').text(data.message);
})
})
$('button').eq(0).click(function () {
//1.设置请求方式, URl, 传递参数, 回调参数
$.post('jquery', {a:100, b:200}, function (data) {
$('#result').text(data.message);
})
})
$('button').eq(2).click(function () {
//jquery通用型方法
$.ajax({
url: 'jquery',
type: 'get',
data: {a: 100, b: 200},
dataType: 'json',
success: function (data) {
$('#result').text(data.message);
},
error: function (data) {
alert("出错了");
}
})
})
</script>
后端接口
@RequestMapping("/jquery")
@ResponseBody
public String jquery(){
Map<String, String> map = new HashMap<>();
map.put("message","hello");
String json = JSON.toJSONString(map);
return json;
}
Axios发送Ajax请求
前端代码
<button>GET</button>
<button>POST</button>
<button>通用型方法ajax</button>
<div id="result">
</div>
<script>
const btnS = document.getElementsByTagName("button");
btnS[0].addEventListener('click', function () {
//get请求
axios.get(
//url路径
'axios',
{
//url参数
params: {
id: 100,
vip: 7
},
//请求头信息
headers: {
name: 'lyj'
}
}).then(value => { //设置响应
console.log(value);
document.getElementById("result").innerHTML = value.data.message;
});
})
btnS[1].addEventListener('click', function () {
//post请求
axios.post(
//url路径
'axios',
{
//请求体参数
data: {
id: 'hello',
name: '张三'
},
//请求头信息
headers: {
name: 'lyj'
},
//设置返回类型
responseType: 'json'
}).then(value => { //设置响应
document.getElementById("result").innerHTML = value.data.message;
});
})
btnS[2].addEventListener('click', function () {
//通用型方法
axios({
method: 'get',
url: '/axios',
params: {
id: 1,
name: "hello"
},
headers: {
username: 'saner',
password: '12323'
}
}).then(value => {
document.getElementById("result").innerHTML = value.data.message;
})
})
</script>
后台代码
@RequestMapping("/axios")
@ResponseBody
public String axios(){
Map<String, String> map = new HashMap<>();
map.put("message","hello");
String json = JSON.toJSONString(map);
return json;
}