原生ajax写法
转自:https://blog.csdn.net/qq_empire/article/details/81737394
相关链接:https://blog.csdn.net/qq_30101879/article/details/77916622
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。原生ajax使用:
function ajax(url){
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : ActiveXObject("microsoft.XMLHttp")
xhr.open("get",url,true);
xhr.send();
xhr.onreadysattechange = () =>{
if(xhr.readystate == 4){
if(xhr.status == 200){
var data = xhr.responseTEXT;
return data;
}
}
}
}
get方式
function btnClick() {
//创建核心对象
xhr= null;
if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {// code for IE6, IE5
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//编写回调函数
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText)
}
}
//open设置请求方式和请求路径
xhr.open("get", "/Ajax/ajax2?username=张三");//一个servlet,后面还可以写是否同步
//send 发送
xhr.send();
}
post
function btnClick() {
//创建核心对象
xhr = null;
if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {// code for IE6, IE5
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//编写回调函数
xhr.onreadystatechange = function() {
/* alert(xmlhttp.readyState); */
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText)
}
/* alert(123); */
}
//open设置请求方式和请求路径
xhr.open("post", "/Ajax/ajax2");//一个servlet,后面还可以写是否同步
//设置请求头
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded")
//send 发送
xhr.send("username=张三");
}

更多精彩