js实现ajax请求

练下手,好久没写ajax

var xmlhttp=null;
//
创建XMLHttprequest function createXMLHttpRequest(){ if(window.ActiveXObject){ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }else{ xmlhttp = new XMLHttpRequest(); } } //开始请求 function startRequest(){ var url="请求的url的地址"; createXMLHttpRequest(); //设置状态改变时所调用的函数 xmlhttp.onreadystatechange = stateChange ; //设置对服务器的调用 xmlhttp.open("POST",url,true); //设置请求头 xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=gb2312");//发送请求 xmlhttp.send(“要提交的内容”); } //监听服务器响应ajax请求 function stateChange(){ if(xmlhttp.readyState==4){ if(xmlhttp.status==200){ //做你想在页面上做的事情 //如果用户名密码正确返回success,错误返回fail if(xmlhttp.responseText=="success"){ document.getElementById("Mess").innerHTML="成功!"; } else{ document.getElementById("Mess").innerHTML="失败!"; } } } }
原文地址:https://www.cnblogs.com/wuguanglin/p/Ajax.html