首先使用express 搭建一个服务器:
const express = require("express");
const app = express();
app.get('/server',function(req,resp){
//设置响应头
resp.setHeader("Access-Control-Allow-Origin","*");
resp.send("hello,Ajax");
})
app.listen(3000,function(){
console.log("服务器已启动,3000端口监听中...")
})
HTML页面如下:Ajax将服务器发出的内容响应给了浏览器页面id为result的div元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax Document</title>
<style>
#result{
width:200px;
height:100px;
border:solid 1px #90b;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
const btn = document.getElementsByTagName("button")[0];
var result = document.getElementById("result");
btn.onclick = function(){
//1.创建对象
const xhr = new XMLHttpRequest()
//2.初始化,设置请求方法和url
xhr.open('GET','http://localhost:3000/server',)
//3.发送
xhr.send();
//4.事件绑定 处理服务端返回的结果
//readystate 是 xhr对象中的属性,表示状态:0,1,2,3,4
xhr.onreadystatechange = function(){
// 判断
if(xhr.readyState == 4){
//判断响应状态码 200 404 403 401 500
if(xhr.status >=200 && xhr.status < 300){
// //处理结果 行 头 空行 体
// console.log(xhr.status);
// console.log(xhr.statusText);
// console.log(xhr.getAllResponseHeader);
// console.log(xhr.response);
//响应
result.innerHTML =xhr.response;
}
}
}
}
</script>
</body>
</html>
moseover响应ajax请求
服务器设置发送信息:
const express = require("express");
const app = express();
app.get('/server',function(req,resp){
//设置响应头
resp.setHeader("Access-Control-Allow-Origin","*");
resp.send("hello,Ajax");
})
app.listen(3000,function(){
console.log("服务器已启动,3000端口监听中...")
})
app.post('/server',function(req,resp){
//设置响应头
resp.setHeader("Access-Control-Allow-Origin","*");
resp.send("hello,Ajax from post");
})
html及js相关代码:
<body> <button>点击发送请求</button> <div id="result"></div> <script> const btn = document.getElementsByTagName("button")[0]; var result = document.getElementById("result"); btn.onclick = function(){ //1.创建对象 const xhr = new XMLHttpRequest() //2.初始化,设置请求方法和url xhr.open('GET','http://localhost:3000/server?a=100&b=200&c=300') //设置请求头 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded") //3.发送 // xhr.send('a=100&b=200&c=300'); xhr.send('a:100,b:200,c;300') //4.事件绑定 处理服务端返回的结果 //readystate 是 xhr对象中的属性,表示状态:0,1,2,3,4 xhr.onreadystatechange = function(){ // 判断 if(xhr.readyState == 4){ //判断响应状态码 200 404 403 401 500 if(xhr.status >=200 && xhr.status < 300){ // //处理结果 行 头 空行 体 // console.log(xhr.status); // console.log(xhr.statusText); // console.log(xhr.getAllResponseHeader); // console.log(xhr.response); //响应 result.innerHTML =xhr.response; } } } } </script> </body>
keydown响应ajax请求并使用json传输数据
设置服务器和需要传输的数据:
app.all('/json-server',function(req,resp){
//设置响应头
resp.setHeader("Access-Control-Allow-Origin","*");
const data ={'name':'atguigu'};
let str = JSON.stringify(data);
resp.send(str);
})
html和js代码如下:
<body>
<div id="result"></div>
<script>
const result = document.getElementById("result");
window.onkeydown =function(){
const xhr = new XMLHttpRequest();
//设置响应体数据类型
xhr.responseType="json";
xhr.open('GET','http://localhost:3000/json-server');
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
//手动对数据转换
// let data = JSON.parse(xhr.response);
// console.log(data);
// result.innerHTML=data.name;
//自动转换(通过设置xml数据响应格式)
result.innerHTML= xhr.response.name;
}
}
}
}
</script>
</body>
解决IE浏览器缓存问题,加上当前实时日期
xhr.open('GET','http://localhost:3000/ie-server?t='+Date.now());
超时及网络异常的Ajax处理:
<body> <button>点击发送请求</button> <div id="result"></div> <script> const btn = document.getElementsByTagName("button")[0]; const result = document.querySelector("#result"); btn.addEventListener('click',function(){ //1.创建对象 const xhr = new XMLHttpRequest(); //超时设置2s xhr.timeout=2000; //超时回调 xhr.ontimeout=function(){ alert("网络异常,请稍后尝试") } //网络异常回调 xhr.onerror = function(){ alert("你的网络似乎出了一些问题") } //2.初始化,设置响应类型和url,解决IE浏览器缓存问题,加上当前实时日期 xhr.open('GET','http://localhost:3000/delay'); //3.发送 xhr.send(); //4.时间绑定 xhr.onreadystatechange=function(){ if(xhr.readyState == 4){ if(xhr.status >=200 && xhr.status < 300){ result.innerHTML = xhr.response; } } } }) </script> </body>
调用abort方法取消ajax请求:
<body> <button>发送请求</button> <button>取消请求</button> <script> const btns = document.querySelectorAll("button"); let xhr = null; //单击事件获取ajax请求 btns[0].onclick = function(){ xhr = new XMLHttpRequest(); xhr.open('GET','http://localhost:3000/delay'); xhr.send(); } //调用abort方法取消ajax请求 btns[1].onclick = function(){ xhr.abort(); } </script> </body>
ajax处理重复请求:
<body> <button>发送请求</button> <script> const btns = document.querySelectorAll("button"); let xhr = null; //标识变量 let isSending = false;//是否正在发送AJAX请求 //单击事件获取ajax请求 btns[0].onclick = function(){ //判断标识变量,如果标识变量为false,则取消当前请求,创建一个新的请求 if(isSending) xhr.abort(); xhr = new XMLHttpRequest(); //修改变量标识 isSending = true; xhr.open('GET','http://localhost:3000/delay'); xhr.send(); xhr.onreadystatechange =function(){ if(xhr.readyState === 4){ isSending = false; } } } </script> </body>
Jquery中的Ajax请求:
<body> <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">通用型方法</button> </div> <script> $("button").eq(0).click(function(){ $.get('http://localhost:3000/jquery-server',{a:100,b:100},function(data){ console.log(data); },'json'); }) $("button").eq(1).click(function(){ $.get('http://localhost:3000/jquery-server',{a:100,b:100},function(data){ console.log(data); }); }) $("button").eq(2).click(function(){ $.ajax({ //url url:'http://localhost:3000/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 }, }) }) </script> </body>
