工作需要自己写了个例子调用SERVLET的,可以运行,
很简单就是一个index.jsp页面,一个GetAndPostExample servlet后台,和WEB.XML配置文件
index.jsp页面
-------------------------------------------------------------------------------------------------------
- <%@pagelanguage="java"import="java.util.*"pageEncoding="gb2312"%>
- <%request.setCharacterEncoding("GB2312");%>
- <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <htmlxmlns="http://www.w3.org/1999/xhtml">
- <head>
- <Metahttp-equiv="Content-Type"content="text/html;charset=gb2312"/>
- <title>AJAX测试</title>
- <mce:scriptlanguage="javascript"><!--
- varxmlHttp;
- //创建xmlHttp
- functioncreateXMLHttpRequest()
- {
- if(window.ActiveXObject)
- xmlHttp=newActiveXObject("Microsoft.XMLHTTP");
- }
- elseif(window.XMLHttpRequest)
- newXMLHttpRequest();
- }
- //拼出要发送的姓名数据
- functioncreateQueryString()
- {
- varfirstName=document.getElementById("firstname").value;
- varmiddleName=document.getElementById("middleName").value;
- varbirthday=document.getElementById("birthday").value;
- varqueryString="firstName="+firstName+"&middleName="+middleName+"&birthday="+birthday;
- returnqueryString;
- //使用get方式发送
- functiondoRequestUsingGET()
- createXMLHttpRequest();
- varqueryString="./GetAndPostExample?";
- queryString=queryString+createQueryString()+"&timeStamp="+newDate().getTime();
- xmlHttp.onreadystatechange=handleStateChange;
- xmlHttp.open("GET",queryString,true);
- xmlHttp.send(null);
- //使用post方式发送
- functiondoRequestUsingPost()
- createXMLHttpRequest();
- varurl="./GetAndPostExample?timeStamp="+ varqueryString=createQueryString();
- xmlHttp.open("POST",url,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
- xmlHttp.send(queryString);
- functionhandleStateChange()
- if(xmlHttp.readyState==4)
- if(xmlHttp.status==200)
- parseResults();
- //解析返回值
- functionparseResults()
- varresponseDiv=document.getElementById("serverResponse");
- if(responseDiv.hasChildNodes())
- responseDiv.removeChild(responseDiv.childNodes[0]);
- varresponseText=document.createTextNode(xmlHttp.responseText);
- alert("后台返回的返回值:"+xmlHttp.responseText);
- responseDiv.appendChild(responseText);
- //--></mce:script>
- </head>
- <body>
- <formid="form1"name="form1"method="post"action="#">
- <p><br/>
- <br/>
- 姓:<inputname="firstName"type="text"id="firstName"/>
- </p>
- <p>
- <label>
- 名:<inputtype="text"name="middleName"id="middleName"/>
- </label>
- </p>
- <p>
- 生日:<inputname="birthday"type="text"id="birthday"/>
- <p></p>
- <inputtype="button"name="Submit"value="GET"onclick="doRequestUsingGET();"/>
- <inputtype="button"name="Submit2"value="POST"onclick="doRequestUsingPost();"/>
- <divid="serverResponse"></div>
- </form>
- </body>
- </html>
GetAndPostExample
copy