AJAX
Global refresh
Partial refresh
Introduction to Ajax
This object is stored in the internal memory of the browser. Use js syntax to create and use the object
-
Asynchronous-multiple requests can be processed at once
-
Javascrip-javascrip script, run in the browser, create an asynchronous object to send a request to update the dom object of the page
-
xml-the data format transmitted in the network, using json to replace the xml data format
XML
Extensible markup language, designed to transmit and store data, label names are all custom, replaced by JSON
Disadvantage
There is no going back, there are cross-domain problems (same-source processing), and SEO is not friendly (the crawler cannot crawl the results)
HTTP protocol
Hypertext Transfer Protocol, which specifies the mutual communication rules and conventions between the browser and the web server
-
Request message
Line POST / URL HTTP/1.1 (request version type)
Head Host: atguigu.com
Cookie:name=guigu
Content-type:application/x-www-form-urlencoded
User-Agent:chrome 83
Blank line
Body username=admin&&password=admin (get can be omitted)
-
Response message
Line HTTP/1.1 200 OK (404-Cannot find 403-No permission 401-Unauthorized 500-Internal error)
头 Content-Type:text/html;charset=utf-8
Content-length:2048
Content-encoding:gzip
Blank line
Body html content
Express framework
It is used to build an express.js server that can be used to access the local request address
asynchronous
Implementation steps of asynchronous objects
-
Create object
var xmlHttp=new XMLHttpRequest();
-
Bind an event onreadystatechange to the asynchronous object
When an asynchronous object initiates a request, this event will be triggered when the data is obtained. This event requires a function to handle state changes
btn.onclick=fun1() //这个函数会被sent(),open()分别进行回调执行 xmlHttp.onreadystatechange=function(){ 处理请求的状态变化 if(xmlHttp.readyState==4&&xmlHttp.status==200){ //可以处理服务器端的数据,更新当前页面 var data=xmlHttp.responseText; //数据更新部分可以使用jquery去实现 document.getElementById("name").value=data; } }
`
异步对象的属性readyState表示异步对象请求状态的变化
-
0: The request is not initialized, create an asynchronous request object var xmlHttp=new XMLHttpRequest()
-
1: Initialize the asynchronous request object, xmlHttp.open (request method, request address, true (asynchronous))
-
2: Asynchronous object sending request xmlHttp.send()
-
3: The asynchronous object receives the response data and returns the data from the server. Internal processing
-
4: The asynchronous request object has parsed the data. Can read data, update page
The attribute status of the asynchronous object indicates the status of the network request 200 (success) 404 (not accessed) 500 (error)
-
Initial asynchronous request object
Asynchronous method open()
xmlHttp.open(请求方式get|post,“请求服务器端的地址”,true(异步)) xmlHttp.open(“get”,“loginServlet?name=zs&&pwd=123”,true);
-
Set request header
xml.sendRequestHeader('Content-Type','application/x-www-form-urlencoded')
-
Set custom request header
-
Solve cross-domain issues
response.setHeader('Access-Control-Allow-Origin', '*');
-
Resolve custom Header request header
response.setHeader('Access-Control-Allow-Headers', '*');
-
-
-
Asynchronous object sending request
xmlHttp.send()
Get the data returned by the server, using the responseText property of the asynchronous object
Use JSON to implement requests
-
Transfer data
const data={name:'aixuexi'} let str=JSON.stringify(data); response.send(str)
-
Modify the data on the html page
-
Manually modify the data
let data = JSON.parse(xhr.response) console.log(data); result.innerHTML = data.name;
-
Automatic modification using xhr attributes
xhr.responseType='json'; result.innerHTML = xhr.response.name;//直接可以获取需要的内容
-
IE cache problem
When sending a request to the server for the first time, the information will be stored in the memory, and the second request may be fetched from the memory, which is not good for timeliness, so this problem needs to be solved
http://127.0.0.1:8000/ie?t=+Date.now()//根据时间戳的不同就会不断发请求给服务器
Timeout and network exception
xml.timeout = 2000;
//延迟回调
xml.ontimeout = function() {
alert("网络异常,稍后重试");
};
//网络异常回调
xml.onerror = function() {
aler("你的网络似乎出了问题");
}
Request cancellation
x.abort();
Cancel repeated server access
Add an identification variable to determine whether the request is in progress
let issending = false;
When a new object is true, it is false after the end of send(), if it is true at the beginning, interrupt x.abort()
Use Jquary to send requests
Implementation of JS files in html pages
//使用bootstrap设置样式,eq(0)表示第几个按钮下标
$('button').eq(0).click(function() {
//使用的get请求方式
$.get('http://127.0.0.1:8000/jquery-server', {
a: 100,
b: 200
}, function(data) {
console.log(data);
}, 'json'); //可以转化为对象的格式,不加则是字符串
});
JSON processing of content in the express framework in JS
const data = { name: '张黑马加油' };
response.send(JSON.stringify(data));
General Ajax request, you can set a lot of return information
$('button').eq(2).click(function() {
$.ajax({
//url访问的地址
url: 'http://127.0.0.1:8000/delay',
//参数
data: {
a: 100,
b: 200
},
//请求类型
type: 'GET',
//响应体结果
dataType: 'json',
//成功DE回调
success: function(data) {
console.log(data);
},
//超时时间
timeout: 2000,
//失败的回调
error: function() {
console.log("出错啦");
}
})
})
Realize sending request with Axios
You can send json data type directly
- GET method
axios.defaults.baseURL = 'http://127.0.0.1:8000';
btns[0].onclick = function() {
axios.get('/axios-server', {
//url参数
params: {
id: 100,
vip: 7
},
//请求头信息
headers: {
name: 'aixuexi',
age: 20
}
}).then(value => {
console.log(value);
})
}
- POST method
btns[1].onclick = function() {
axios.post( //url参数
'axios-server', {
username: 'admin',
password: 'admin'
}, {
params: {
id: 200,
vip: 9
},
//请求头信息
headers: {
heigh: 180,
weigh: 180,
}
},
);
};
- AJAX method
btns[2].onclick = function() {
axios({
//请求方式
type: 'GET',
//url参数
url: 'axios-server',
params: {
id: 300,
vip: 8
},
headers: {
a: 400,
b: 500
},
data: {
username: 'zll',
password: 'zll'
}
}).then(response => {
console.log(response);
})
}
- Use the fetch function to send objects
Talk about cross-domain issues in detail
Same Origin Strategy
Security policy, the protocol, domain name and port number of the requested URL and the server URL must be exactly the same
Cross-domain issues
Violation of the same-origin policy is cross-domain, a.com sends to b.com; 3000 sends a request to 8000
JSONP solves cross-domain problems
Is to use a piece of js code to return the data we want, this js code processing is implemented on the server side
CORS cross-domain solution
By setting an HTTP response header to tell the browser that the access needs to be cross-domain