ajax
ajax
-
get 方法
// 请求数据 function get1(string) { // 兼容写法 let xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.onreadystatechange = function() { // async 为true时,需要指定onreadystatechange事件中的执行函数 if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }; xhr.open("GET", "./index.html" + string, true); // true 代表异步执行 xhr.send(); } // 请求数据,从新加载而不是从缓存中读取 // 改变请求url,加Math.random() function get2() { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { // async 为true时,需要指定onreadystatechange事件中的执行函数 if (this.readyState === 4 && this.status === 200) { console.log(this.responseText); } }; xhr.open("GET", "./index.html?t=" + Math.random(), true); xhr.send(); } // get 提交信息,信息?key=value function get3() { let xhr = new XMLHttpRequest(); xhr.open("GET", "./index.html?name=achilles&age=18", false); xhr.send(); // async 为false的时候,不用编写 onreadystatechange 执行函数,直接把代码放到send 后面即可 console.log(this.responseText); }
-
post 方法
// 请求数据 function post1() { let xhr = new XMLHttpRequest(); // async 为true时,需要指定onreadystatechange事件中的执行函数 xhr.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { console.log(xhr.responseText); } }; xhr.open("POST", "./index.html", true); xhr.send(); } // 提交数据 function post2() { let xhr = new XMLHttpRequest(); // async 为true时,需要指定onreadystatechange事件中的执行函数 xhr.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { console.log(xhr.responseText); } }; xhr.open("POST", "./index.html", true); // 设置http请求头 xhr.setRequestHeader("Content-Type", "application/json"); // 发送的数据 xhr.send("name=achilles&age=19"); }