日期:2014-05-16 浏览次数:20741 次
var $= { createXmlHttp : function () { var xmlHttp = null; try { xmlHttp = new XMLHttpRequest(); } catch (e) { try { xmlHttp = new ActiveXObject('Msxml2.XMLHTTP'); }catch (ee) { xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); } } return xmlHttp; }, ajax: function(ajaxInfo) { var xmlObj = $.createXmlHttp(); if (!xmlObj){ alert("很抱歉,你的浏览器暂时不支持Ajax。"); return; } var method = ajaxInfo.method.toUpperCase(); var method=ajaxInfo.method; var data = null; xmlObj.open(method,ajaxInfo.url, true); if(method == "POST"){ data = ajaxInfo.data; xmlObj.setRequestHeader("CONTENT-TYPE", "application/x-www-form-urlencoded"); } xmlObj.send(data); xmlObj.onreadystatechange = function () { if(xmlObj.readyState == 4) { if(xmlObj.status == 200) { var type = ajaxInfo.type.toUpperCase(); if(type == "TEXT") { ajaxInfo.success(xmlObj.responseText); }else if(type == "XML") { ajaxInfo.success(xmlObj.responseXML); }else{ alert("无法识别的返回方式"); } xmlObj = null; } } }; } }
$.ajax({ method:"POST", url:"servlet/AjaxServlet?time="+new Date().getTime(), data:"username=abc&password=123", type:"TEXT", success:function (data) { var jason = data ; alert(jason); } });
$.ajax({ method:"GET", url:"servlet/AjaxServlet?username=abc&password=123&time="+new Date().getTime(), data:null, type:"TEXT", success:function (data) { var jason = data ; alert(jason); } });
package com.lrh.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username=request.getParameter("username"); String password=request.getParameter("password"); PrintWriter out=response.getWriter(); if(username.equals("abc")&&password=="123"){ System.out.println("该用户已经存在"); out.print("该用户已被注册!"); } out.flush(); } }
<servlet> <servlet-name>AjaxServlet</servlet-name> <servlet-class>com.lrh.servlet.AjaxServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AjaxServlet</servlet-name> <url-pattern>/servlet/AjaxServlet</url-pattern> </servlet-mapping>