当前位置: 代码迷 >> Ajax >> 用ajax作的HelloWorld
  详细解决方案

用ajax作的HelloWorld

热度:514   发布时间:2012-09-04 14:19:30.0
用ajax做的HelloWorld
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'ajax.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">    

	<script type="text/javascript">
		function ajaxSubmit()
		{
			var xmlHttpRequest = null;//声明一个对象以接受XmlHttpRequest对象
			
			if(window.ActiveXObject)//IE浏览器
			{
				xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");					
			}	
			else if(window.XMLHttpRequest)//除IE外的其它浏览器
			{
				xmlHttpRequest = new XMLHttpRequest();
			}
			if(null != xmlHttpRequest)
			{
				xmlHttpRequest.open("GET","AjaxServlet",true);
				//关联好ajax的回调函数
				xmlHttpRequest.onreadystatechange = ajaxCallback;
				
				//真正向服务器发送数据
				xmlHttpRequest.send(null);
			}
			
			
			function ajaxCallback()
			{
				if(xmlHttpRequest.readyState==4){
     				if(xmlHttpRequest.status==200){
     					var responseText = xmlHttpRequest.responseText;
     					document.getElementById("div1").innerHTML = responseText;
     				}
     			}

			}
		}
		
	</script>
	
  </head>
  
  <body>
	<input type="button" value="返回值"  onclick="ajaxSubmit();">
	<div id="div1"></div>
  </body>
</html>

?

package com.javasky.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AjaxServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		
		System.out.println("doGet invoked!");
		
		out.println("Hello World");
		
		out.flush();
		
		
		
		
	}
}

?

  相关解决方案