Ajax 的核心是 XMLHttpRequest 对象
创建对象
let xhttp = new XMLHttpRequest();
XMLHttpRequest 对象方法
方法 | 描述 |
---|
new XMLHttpRequest() | 创建新的 XMLHttpRequest 对象 |
abort() | 取消当前请求 |
getAllResponseHeaders() | 返回头部信息 |
getResponseHeader() | 返回特定的头部信息 |
open(method, url, async, user, psw) | 规定请求method:请求类型 GET 或 POSTurl:文件位置async:true(异步)或 false(同步)user:可选的用户名称psw:可选的密码 |
send() | 将请求发送到服务器,用于 GET 请求 |
send(string) | 将请求发送到服务器,用于 POST 请求 |
setRequestHeader() | 向要发送的报头添加标签/值对 |
请求
方法 | 描述 |
---|
open(method, url, async) | 规定请求的类型method:请求的类型:GET 还是 POSTurl:服务器(文件)位置async:true(异步)或 false(同步) |
send() | 向服务器发送请求(用于 GET) |
send(string) | 向服务器发送请求(用于 POST) |
onreadystatechange | 服务器响应(this) |
ontimeout | 超时处理 |
xhttp.open("GET", "url", true);
xhttp.send();
xhttp.open("POST", "ajax_test.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Bill&lname=Gates");
xhttp.open("POST", "ajax_test.asp", true);
var fd = new FormData()
fd.append('companyId', '43400051')
xhttp.send(fd);
xhttp.open("post", "http://10.2.112.20:38763/er/atlas/", true);
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.send(JSON.stringify(
{ companyId: "43400051" }
));
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(this.response))
}
};
xhttp.ontimeout = function(event){
alert('请求超时!')
}