<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" οnclick="doRequestUsingGET()" /><br/>
<input type="button" value="POST" οnclick="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"));
}
%>