var williaml; if(window.XMLHttpRequest) { //for IE7,Firefox,Chrome,Opera,Safari william=new XMLHttpRequest(); } else { //for IE6,IE5 william=new ActiveXObject("Microsoft.XMLHTTP"); }
2.如果要把请求发送到服务器,使用XMLHttpRequest的open()和send()方法
GET
<html> <head> <script type="text/javascript"> function loadXMLDoc() { var william; if(window.XMLHttpRequest) { william=new XMLHttpRequest(); } else { william=new ActiveXObject("Microsoft.XMLHTTP"); } william.onreadystatechange=function() { if(william.readyState==4&&william.status==200) { document.getElementById("my").innerHTML=william.responseText; } } william.open("GET","/ajax/demo.asp?name=bill&age=56",true); william.send(); } </script> </head> <body> <h2>AJAX</h2> <button type="button" onclick="loadXMLDoc()">请求数据</button> <div id="myDiv"></div> </body> </html>
<html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("POST","/ajax/demo_post2.asp",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("fname=Bill&lname=Gates"); } </script> </head> <body> <h2>AJAX</h2> <button type="button" onclick="loadXMLDoc()">请求数据</button> <div id="myDiv"></div> </body> </html>
在与后台交互的时候,通常是这样子写:(找了个例子)
$.ajax({ type : "POST", //请求方法 contentType : "application/json", //发送到服务器的数据的编码类型 dataType : "json", //预期返回类型 url : "searchController.do?getValidateCode&phoneCode="+$("#accountPhone").val(),// 当前页地址。发送请求的地址 success : function(data) { //请求成功后的回调函数 if(!data.success){ alert(data.obj); } }, error : function() { //请求失败时调用此函数 alert("抱歉,暂时无法为您提供这项服务。"); } });