1. 程式人生 > >Ajax中的兩種傳參方式詳解

Ajax中的兩種傳參方式詳解

1.建立servlet類,路徑設定為ajax01,程式碼如下:

package com.cdsxt.ajax;

import java.io.IOException;

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

public class AjaxAction01 extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5463256742759467859L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/**
		 * 測試get方式傳入引數
		 */
		
		String username = request.getParameter("username");

		System.out.println("username:"+username);
		
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		response.getWriter().write(username);
	}

}

2.在WebRoot下面建立一個jsp檔案,程式碼如下:
<%@ 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 'index.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">
	<script type="text/javascript">
	
		/**
		
			post方式傳入引數
			ajax基本步驟
			第一步:建立XMLHttpRequest物件
			第二步:寫監聽函式
			第三步:開啟請求
			第四部:傳送請求
			
		*/
		
		function testAajx(){
			
			var input = document.getElementById("uname");
			var value = input.value;
			//if(!value){
				//return ;
			//}
			
			//建立一個請求物件
			var request;
			//為了處理瀏覽器的差異性問題
			//第一個更通用  判斷window物件中是否含有 XMLHttpRequest物件   如果有  則直接new出來使用
			//如果沒有  則表示是ie瀏覽器  要採用特殊的方式進行建立
			if(window.XMLHttpRequest){
				//建立物件
				request = new XMLHttpRequest();
			}else if(window.ActiveXObject){
				request = new ActiveXObject("Msxml2.XMLHTTP");
			}
			//監聽函式   是一個回撥函式
			request.onreadystatechange = function (){
				//判斷request物件的狀態
				//判斷http狀態  如果狀態為4  則表示  request物件已經完成
				
				//得到要顯示資料的容器  (DOM)
				var div = document.getElementById("msg");
				if(request.readyState == 4){
					if(request.status == 200){
						// 對資料的操作
						//顯示資料
						div.innerHTML = request.responseText;
					}else if(request.status == 404){
						div.innerHTML = "資源不存在!";
					}else if(request.status == 500){
						div.innerHTML = "資源感冒了!";
					}
					
				}else{
					div.innerHTML = "<img src=\"assets/images/loading.gif\" />";
				}
				
			};
			
			//第一個引數   表示 提交方式
			//第二個引數  表示提交的地址
			//第三個引數  表示是否位同步   預設值是 true  如果為false  表示同步   是可選的
			//第四個和第五個引數  表示  basic認證所需的使用者名稱和密碼   不常用
			//如果在引數中存在特殊字元  則需要用encodeURIComponent進行轉碼
			//ajax01?username=zhangsan#lisi
			request.open("post", "ajax01");
			
			/**
			
				關於POST方式傳值
				
				需要將引數組合到send方法中  組織結構  為  name1=value1&name2=value2...
				
				並且一定要設定  request的header為application/x-www-form-urlencoded
				
				而且一定要將request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				放在open方法和send方法之間
			
			*/
			
			request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			
			//傳送請求
			//get方式   需要傳入null
			//post傳值
			request.send("username=lisi#zhangsan&password=123123");
			
			
			
			/**
			
				get方式和post方式傳引數
				
				get方式:
					需要將引數放到open方法中   換句話說  就是將引數放在url後面
					傳遞方式  相當於在位址列上面傳入引數  如果 在傳輸的工程中  存在特殊字元  需要用encodeURIComponent進行轉碼
					
					
				post方式:post方式也可採用get的方式傳引數
				
					不同的是    post方式更多的是將引數  放在 send方法中傳輸   但是 和get方式的引數組織方式相同
					
					如果要想用post將引數傳入後臺  一定要在  open方法和send方法之間  呼叫setRequestHeader  進行設定頭資訊
					將引數編碼方式設定為和普通form表單一樣
			
			*/
			
			
		}
	
	</script>
  </head>
  
  <body>
  
  	<!--  <form action="" enctype="application/x-www-form-urlencoded"></form>-->
    <input type="text" id="uname"><input type="button" value="testAjax" onclick="testAajx()">
    <div id="msg"></div>
  </body>
</html>

3.載入伺服器,觀察get和post的兩種傳參方式。