ajax原生js实现post

function ajax2() {
//原生写法,post请求,不可以带数据
//1.创建XMLHttpRequest对象
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();//火狐,谷歌浏览器等
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");//IE浏览器
}
//2.使用open方法建立与服务器的链接
xmlHttp.open("POST","ajaxServlet",true);//true表示异步请求,false表示同步
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.send("username=小明");
//3.在回调函数中对服务器响应的数据进行处理
xmlHttp.onreadystatechange=function() {
//判断status响应状态码是否为200,readyState 就绪码是否是4
if(xmlHttp.status==200 && xmlHttp.readyState==4){
//获取服务器返回的内容,响应的结果
//获取服务器返回的内容
var responseText = xmlHttp.responseText;
alert(responseText)
}else{
alert("服务器异常...")
}
}


<body>
<input type="button" value="发送请求" onclick="ajax()">
请输入:<input type="text">
</body>
 
posted @ 2021-09-23 20:58  张三疯321  阅读(445)  评论(0编辑  收藏  举报