ajax与servlet之间的交互方式

2017-10-23 11:48:02来源:CSDN作者:weixin_35982117人点击

分享
第七城市

1.配置web.xml:

<servlet>  <servlet-name>ActionServlet</servlet-name>  <servlet-class>web.ActionServlet</servlet-class> </servlet> <servlet-mapping>  <servlet-name>ActionServlet</servlet-name>  <url-pattern>*.do</url-pattern> </servlet-mapping>

2.编写servlet类 ActionServlet:

public void service(HttpServletRequest request,HttpServletResponse response)    throws ServletException,IOException{    request.setCharacterEncoding("UTF-8");    response.setContentType("text/html;charset=UTF-8");    PrintWriter out=response.getWriter();    String uri=request.getRequestURI();    String action=uri.substring(uri.lastIndexOf("/")            , uri.lastIndexOf("."));if(action.equals("/wenda")){        wendalistDAO dao=new wendalistDAO();        try{            List<wendalist>all=dao.findAll();            JSONArray arry=JSONArray.fromObject(all);            out.println(arry.toString());        }catch (Exception e) {            e.printStackTrace();            throw new ServletException(e);        }        }if(action.equals("/wenti")){                wentiSaveDAO dao=new wentiSaveDAO();            String q=request.getParameter("name");//获取jsp传来的值            String d=request.getParameter("name2");            try {if(username!=null){                dao.save();            }            } catch (Exception e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }}

3.在jsp中获取后台传递的值:

function getXmlHttpRequest(){    var xhr=null;    if((typeof XMLHttpRequest)!='undefined'){    xhr=new XMLHttpRequest();    }else{        xhr=new ActiveXObject("Microsoft.XMLHttp");        }    return xhr;}function f1(){    var xhr=getXmlHttpRequest();    xhr.onreadystatechange=function(){        if(xhr.readyState==4){            var txt=xhr.responseText;//获取后台传来的值            var q=txt.evalJSON();//json解析            //这里进行对html的操作                }            };        xhr.open('post','wenda.do',true);//ture表示异步        xhr.setRequestHeader("Content-Type",        "application/x-www-form-urlencoded");        xhr.send(null);    }

4.在jsp中向后台传值:

function f2(){    var xhr=getXmlHttpRequest();    xhr.onreadystatechange=function(){        if(xhr.readyState==4){        alert("提交成功");        }        };        xhr.open('post','wenti.do',true);        xhr.setRequestHeader("Content-Type",        "application/x-www-form-urlencoded");        xhr.send("name="+v1+"&name2="+Dt);}       
第七城市

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台