XMLHttpRequest

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();

//发送formData -- 对应Postman Body-formdata
xhttp.open("POST", "ajax_test.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Bill&lname=Gates");

//发送formData(不用设置Content-Type) -- 对应Postman Body-formdata
xhttp.open("POST", "ajax_test.asp", true);
var fd = new FormData()
fd.append('companyId', '43400051')
xhttp.send(fd);

//发送JSON数据 -- 对应Postman Body-raw-JSON
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" }
)); 

//当 readyState 为 4,status 为 200 时
xhttp.onreadystatechange = function() {
	if (this.readyState == 4 && this.status == 200) {
		console.log(JSON.parse(this.response))
	}
};
//超时处理
 xhttp.ontimeout = function(event){
     alert('请求超时!')
 }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值