什么是 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
2
3
4
5
6
7
8
9
10
//	new Browser
let httpRequest = new XMLHttpRequest();// create a XMLHttp obj
/*连接建立, 声明接收到服务器回传的数据要调用的函数*/
httpRequest.onreadystatechange = function(){
//响应服务器
};

httpRequest.open("GET", url);//放入请求方法 get, post ... , 参数2:发送网址

httpRequest.setRequestHeader("Content-Type", "application/json");//报头, 这个里面声明发送的数据个数为 json

处理响应

1
2
3
4
5
6
7
8
9
httpRequest.onreadystatechange = function(){
//响应服务器

if(httpRequest.readyState === XMLHttpRequest.DONE){
if(httpRequest.status === 200){
//ready perfect!
}
}
};

针对项目

  • 登陆和创建用户都需要emailpassword两个值,不如直接将它抽象成一个User构造器:

    1
    2
    3
    4
    function User(email, password){
    this.email = email;
    this.password = password;
    }

    前台和后台利用 json 传输数据,可以将其抽象称为一个makeRequest函数,并指定getRequest函数作为接受后响应处理的函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    function 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);
    }
相关文章
评论
分享
Please check the post_relate setting in config.yml of hexo-theme-Annie! You should make sure 'postsEnable == true' and the number of site posts greater than 1.
Please check the comment setting in config.yml of hexo-theme-Annie!