欢迎来到天天文库
浏览记录
ID:59117203
大小:126.33 KB
页数:8页
时间:2020-09-13
《ajax编程实践之与服务器通信.pdf》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、ajax编程实践之与服务器通信AJAX编程实践之与服务器通信首先看下看下相对简单些的--向服务器发送一个包含有名/值对的简单查询串,在这种情况下XHP即可以用GET也可以用POST。GETfunctiondoRequestUsingGET(){createXMLHttpRequest();varqueryString="GetAndPostExample?";queryString=queryString+createQueryString()+"&timeStamp="+newDate().getT
2、ime();xmlHttp.onreadystatechange=handleStateChange;xmlHttp.open("GET",queryString,true);xmlHttp.send(null);}POSTfunctiondoRequestUsingPOST(){createXMLHttpRequest();varurl="GetAndPostExample?timeStamp="+newDate().getTime();varqueryString=createQueryStrin
3、g();xmlHttp.open("POST",url,true);xmlHttp.onreadystatechange=handleStateChange;xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xmlHttp.send(queryString);}queryString就是名/值对的参数形式了(如name=LiLin&age=23),在调用OPEN方法中,当请求方法是用POST的时候为
4、了确保服务器知道请求体中有请求参数,需要调用setRequestHeader,将Content-Type值设置为application/x-www-form-urlencoded.当然也可不放在请求体中(那就不要用POST啦!)此时server处理:importjava.io.*;importjava.net.*;importjavax.servlet.*;importjavax.servlet.http.*;publicclassGetAndPostExampleextendsHttpServlet
5、{protectedvoidprocessRequest(HttpServletRequestrequest,HttpServletResponseresponse,Stringmethod)throwsServletException,IOException{//Setcontenttypeoftheresponsetotext/xmlresponse.setContentType("text/xml");//Gettheuser'sinputStringfirstName=request.getP
6、arameter("firstName");StringmiddleName=request.getParameter("middleName");Stringbirthday=request.getParameter("birthday");//CreatetheresponsetextStringresponseText="Hello"+firstName+""+middleName+".Yourbirthdayis"+birthday+"."+"[Method:"+method+"]";//Wr
7、itetheresponsebacktothebrowserPrintWriterout=response.getWriter();out.println(responseText);//Closethewriterout.close();}protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{//Processtherequestinmet
8、hodprocessRequestprocessRequest(request,response,"GET");}protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{//ProcesstherequestinmethodprocessRequestprocessRequest(request
此文档下载收益归作者所有