<script type="text/javascript">
var xmlHttp;
/*建立非同步對象,根據瀏覽器區別建立*/
function createXmlHttpRequest(){
if(window.ActiveObject){
xmlHttp=new ActiveObject("Microsoft.XMLHttp");
}else if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}
}
//readyState:請求的狀態,4為資料接收成功
//伺服器返回的http請求響應值,200表示請求成功
//對返回的資料進行decodeURI解碼
function handleStateChange(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
var responseDiv=document.getElementById("serverResponse");
responseDiv.innerHTML=decodeURI(xmlHttp.responseText);
}
}
//對發送的參數進行兩次encodeURI編碼
function createQueryString(){
var firstName=document.getElementById("firstName").value;
var birthday=document.getElementById("birthday").value;
var queryStr="firstName="+firstName+"&birthday="+birthday;
return encodeURI(encodeURI(queryStr));
}
//get請求的方法,請求的url後面帶參數,sendd(null)方法中傳null值。
function doRequestUsingGET(){
createXmlHttpRequest();
var queryString="test.jsp?";
queryString+=createQueryString()+"×tamp="+new Date().getTime();
xmlHttp.onreadystatechange=handleStateChange;
alert(queryString);
xmlHttp.open("GET",queryString);
xmlHttp.send(null);
}
//post請求的方法,參數傳在send方法中
function doRequestUsingPOST(){
createXmlHttpRequest();
var url="test.jsp?timestamp="+new Date().getTime();
var queryString=createQueryString();
xmlHttp.open("post",url);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send(queryString);
}
</script>
</head>
<body>
<h2>請輸入姓名和生日</h2>
<form action="">
<input type="text" id="firstName" /><br/>
<input type="text" id="birthday" />
</form>
<form action="">
<input type="button" value="GET" onclick="doRequestUsingGET()" /><br/>
<input type="button" value="POST" onclick="doRequestUsingPOST()"/>
</form>
<div id="serverResponse"></div>
</body>
伺服器段的代碼如下:
<%
if(request.getMethod().equals("POST")){
response.getWriter().write("post方式提交"+request.getParameter("firstName"));
}else if(request.getMethod().equals("GET")){
response.getWriter().write("get方式提交"+request.getParameter("firstName"));
}
%>