使用原生JS对象XMLHttpRequest,进行异步请求

如果还只会JQ中的AJAX接口,而不知道底层,感觉有点辣鸡,所以自己用底层XMLHttpRequest对象去访问服务器。

那么直奔主题吧

前端代码:(这里唯一的缺点是,发送的数据格式跟JQ的不太一样,估计JQ做了处理)

var xmlHttpRequest;
function myAjax(){
	var url = "<%=basePath%>/hmcp/hightvalue/purchase/hmcpPurchaseApply/batchPurchase.spring";
	xmlHttpRequest = new XMLHttpRequest();
	xmlHttpRequest.onreadystatechange = myCallBack;
	//相应数据格式
	xmlHttpRequest.responseType = "json";
	//请求方式和地址,是否异步
	xmlHttpRequest.open("post",url,true);
	//注意:setRequestHeader方法,只能在open方法后面调用
	xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlHttpRequest.send("followIds[]=1&followIds[]=2");
}
//回调函数
function myCallBack(){
//XMLHttpRequest.DONE=4
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
		//成功后的逻辑
	}
}

 

后台:

使用原生JS对象XMLHttpRequest,进行异步请求

 

文档:

MDN:XMLH TTP 请求

how2j.cn:AJAX教程