什么是 AJAX
?
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the
XMLHttpRequest
object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX’s most appealing characteristic is its “asynchronous” nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.
如何发送HTTP
请求?
1 | // new Browser |
处理响应
1 | httpRequest.onreadystatechange = function(){ |
针对项目
登陆和创建用户都需要
email
和password
两个值,不如直接将它抽象成一个User
构造器:1
2
3
4function User(email, password){
this.email = email;
this.password = password;
}前台和后台利用
json
传输数据,可以将其抽象称为一个makeRequest
函数,并指定getRequest
函数作为接受后响应处理的函数1
2
3
4
5
6
7
8
9function makeRequest(User, url) {
let httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = getRequest;
httpRequest.open("POST", url);
httpRequest.setRequestHeader("Content-Type", "application/json");
let json = JSON.stringify(User);
httpRequest.send(json);
}