最常用的ajax代码
来源:互联网 发布:过期未注册域名 编辑:程序博客网 时间:2024/06/05 08:32
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>client.html</title> <script language="JavaScript" type="text/javascript"> var xmlreq = false; // ---------------初始化XMLHttpRequest-------------------- function createXMLHttpRequest(){ if (window.XMLHttpRequest) { //不是ie浏览器 xmlreq = new XMLHttpRequest(); } else if (window.ActiveXObject) { //IE try { xmlreq = new ActiveXObject("Msxml12.XMLHTTP"); } catch (e1) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { // Unable to create an XMLHttpRequest with ActiveX } } } } //------------发送XMLHttpRequest请求----------------- //GET提交请求 function sendRequestGet(url){ createXMLHttpRequest(); xmlreq.open("get",url,true); xmlreq.onreadystatechange = processResponse;//响应请求函数 xmlreq.send(null); } //POST提交请求 function sendRequestPost(url,param){ createXMLHttpRequest(); xmlreq.open("post",url,true); xmlreq.onreadystatechange = processResponse;//响应请求的函数 xmlreq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlreq.send(param); } function sendRequest(url,param,method){ if(method){ if (method.toLowerCase("get")) { sendRequestGet(url + "?" + param); } else if (method.toLowerCase("post")) { sendRequestPost(url, param); } }else{ alert("method is null"); } } //---------响应请求的函数------------ function processResponse(){ if(xmlreq.readyState == 4){ if(xmlreq.status == 200){ alert(xmlreq.responseText); }else{ alert("发送失败!") } } } //事件响应 function submitRequest(){ var form1 = document.getElementById("form1"); var url = form1.action; var username = form1.username.value; var password = form1.password.value; var method = form1.method; var param = "username=" + username + "&password=" + password; sendRequest(url, param, method); } </script> </head> <body> <form action="server.aspx" method="post" name="form1" id="form1"> 用户名:<input name="username" id="username" type="text"> <br> 密 码:<input name="password" id="password" type="text"> <br> <input type="button" value="发送信息" onclick="submitRequest()"> </form> </body></html>