1. 程式人生 > >ajax案例---以GET和POST方式非同步提交資料給後臺

ajax案例---以GET和POST方式非同步提交資料給後臺

前臺頁面程式碼

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>ajax demo</title>

	<script type="text/javascript">
		var xmlHttpRequest = null;

		function ajaxSubmit(){
		//	window.alert(window.ActiveXObject);
			
			if(window.ActiveXObject){	//是IE瀏覽器

				xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");

			}else if(window.XMLHttpRequest){	//除IE外的其他瀏覽器

				xmlHttpRequest = new XMLHttpRequest();
			}

			/*
				使用Ajax準備向伺服器端傳送一個請求
			*/
			if(null != xmlHttpRequest){	//使用GET方式,			//非同步
				var num1 = document.getElementById("num1").value;
				var num2 = document.getElementById("num2").value;
				
				
			//	xmlHttpRequest.open("GET", "AjaxServlet?num1=" + num1 + "&num2=" + num2, "true");

				xmlHttpRequest.onreadystatechange = ajaxCallBack;	//註冊一個回撥函式

				//向伺服器端傳送資料
			//	xmlHttpRequest.send(null);	//get方式設定為null

				//post方式
				xmlHttpRequest.open("POST", "AjaxServlet", "true");
				//使用post方式提交資料,必須加上下面這行程式碼
				xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				
				xmlHttpRequest.send("num1=" + num1 + "&num2=" + num2);

			}
		}

		function ajaxCallBack(){

			if(xmlHttpRequest.readyState == 4){

				if(xmlHttpRequest.status == 200){
					var responseText = xmlHttpRequest.responseText;
				
					document.getElementById("content").innerHTML = responseText;	
				}
			} 
		}

		
	</script>

  </head>
  
  <body>
	<input type="text" name="num1" id="num1"/> <br/>
	<input type="text" name="num2" id="num2"/> <br/>
	
	<input type="button" value="從服務區端獲取資料" onclick="ajaxSubmit();"/>

	<div id="content"></div>
  </body>

</html>

後臺處理程式碼
package com.ajax.test;

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 {

		response.setContentType("text/html");

		String num1 = request.getParameter("num1");
		String num2 = request.getParameter("num2");
		
		int num3 = Integer.valueOf(num1) + Integer.valueOf(num2);
		
		PrintWriter out = response.getWriter();
		
		System.out.println("AjaxServlet.doGet()");
		
		out.println(num3);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		System.out.println("AjaxServlet.doPost()");
		
		this.doGet(request, response);
	}
}