1、创建ajax引擎。
function createXMLHttp(){ var xmlHttp; if(window.ActiveXObject){ xmlHttp = new ActiveXObject("Microsoft.XMLHttp"); }else{ xmlHttp = new XMLHttpRequest(); } return xmlHttp; }
代码解析,首先创建xmlHttp对象,在IE浏览器下使用的是ActiveX控件封装方式,将类名字作为参数传入即可,就会自动找到并创建对象。
非IE下,通过XMLHttpRequest类直接创建即可。
2、get请求服务器数据。
例如我们实现一个案例:点击按钮请求服务器,服务器接到请求后告诉浏览器我收到了。
document.getElementById("btn").onclick = function(){ var xmlHttp = createXMLHttp(); xmlHttp.open("get","/Ajax/ajax.do?name=zhangsan", true); xmlHttp.send(); xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState == 4){ if(xmlHttp.status == 200){ document.getElementById("status").innerHTML = xmlHttp.responseText; } } } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); System.out.println(name); PrintWriter out = response.getWriter(); out.print(name+" I get it"); out.flush(); out.close(); }
以上的get请求不支持中文,若要中文不乱吗,可以这样处理。
document.getElementById("btn").onclick = function(){ var xmlHttp = createXMLHttp(); //get请求对中文的处理,需要使用encodeURIComponent xmlHttp.open("get","/Ajax/ajax.do?name="+encodeURIComponent("张三"), true); xmlHttp.send(); xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState == 4){ if(xmlHttp.status == 200){ document.getElementById("status").innerHTML = xmlHttp.responseText; } } } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); //转换为UTF-8就没有了乱码 name = new String(name.getBytes("ISO8859-1"), "UTF-8"); //这几句指定返回的格式和编码,并且告诉浏览器不要缓存(对IE) response.setContentType("text/html;charset=UTF-8"); response.setHeader("pragma", "no-cache"); response.setHeader("cache-control", "no-cache"); response.setHeader("expires", "0"); PrintWriter out = response.getWriter(); out.print(name+"我收到了"); out.flush(); out.close(); }
3、post请求服务器数据。
document.getElementById("btn").onclick = function(){ var xmlHttp = createXMLHttp(); //post请求不需要url参数 xmlHttp.open("post","/Ajax/ajax.do", true); //Post请求需要设置请求头部 xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //post请求传参数在send中指定 xmlHttp.send("name=张三"); xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState == 4){ if(xmlHttp.status == 200){ document.getElementById("status").innerHTML = xmlHttp.responseText; } } } }
在post请求时,
①、在open中指定post,并且传入的url不需要再带参数
②、设置post请求头
③、如需带参数,需要在send中指定参数。
④、支持中文。
服务器端:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); System.out.println(name); PrintWriter out = response.getWriter(); out.print(name+",我收到了"); out.flush(); out.close(); }