Ajax Simple Demo

Ajax Simple Demo

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'ajax2.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
		var xmlHttpRequest = null;
		
		function ajaxSubmit(){
			if(window.ActiveXObject){
				xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}else{
				xmlHttpRequest = new XMLHttpRequest();
			}
			
			if(null != xmlHttpRequest){
				var v1 = document.getElementById("v1").value;
				var v2 = document.getElementById("v2").value;
				
				//xmlHttpRequest.open("GET","servlet/AjaxServlet2?v1=" + v1 + "&v2=" + v2,true);
				xmlHttpRequest.open("POST","servlet/AjaxServlet2",true);
				
				xmlHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
				xmlHttpRequest.onreadystatechange = ajaxCallback;
				xmlHttpRequest.send("v1=" + v1 + "&v2=" + v2);
			}
		}

		function ajaxCallback(){
			if(xmlHttpRequest.readyState == 4){
				if(xmlHttpRequest.status == 200){
					var responseText = xmlHttpRequest.responseText;
					alert(responseText);
					document.getElementById("div1").innerHTML=responseText;					
				}
			}
		}
		
	</script>
  </head>
  
  <body>
  	<input type="text" name="value1" id="v1"><br>
  	<input type="text" name="value2" id="v2"><br>
  	<input type="button" value="get text" onclick="ajaxSubmit();"><br>
  	<form action="" enctype="application/x-www-form-urlencoded"></form>
  	<div id="div1"></div>
  </body>
</html>
 

 

你可能感兴趣的:(Ajax JavaScript)