1. 程式人生 > >原生js + ajax + Servlet傳遞引數

原生js + ajax + Servlet傳遞引數

使用原生JS + Ajax + Servlet (實現從前端接收資料)

前端 Jsp 頁面

index.jsp

<form action="" method="post">
    <div>
        <span>用 戶 名 </span>
        <input type="text" id="username" nam
   e="username" value="請輸入使用者名稱">
    </div>
    <div id="info"></div>
    <script type="text/javascript">
        var input = document.getElementsByTagName('input')[0];
        var info = document.getElementById('info');
        var username = "";
        var str = "";
        input.onfocus = function() {
            if (this.value == "請輸入使用者名稱") {
                this.value = "";
                this.style.color = "#111111";
            }
        };
        input.onblur = function() {
            if (this.value == "") {
                this.value = "請輸入使用者名稱";
                this.style.color = "#999999";
            } else {
                this.style.color = "#424242";
            }

           //當文字框失去焦點時,儲存文字框輸入內容,

           //否則提交表單會清空文字框內容,Servlet接收不到資料

           username = input.value;
           str = "username=" + username;
        };
    </script>
    <input type="submit" name="Submit1" value="提交"
        onclick="doPost('servlet/NewServlet', str, info);">
</form>

JS Ajax

//封裝相容XMLHttpRequest

function XHRObj() {
    if (window.XMLHttpRequest) {
        // 除了IE6及以下
        return new XMLHttpRequest();
    } else {
        // 若為IE6及以下
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

// 封裝callback函式

function loadReq(xmlObj, url, callback, str) {
    this.xmlObj = XHRObj();

 /**
   * 此處重點 你給的url是字串!!!
   * 需要使用 encodeURI() 函式可把字串作為 URI 進行編碼才能解析。 
   * 否則返回值就是 null(這還是好的)!|| 其他奇怪的東西
   * URIstring 的副本,其中的某些字元將被十六進位制的轉義序列進行替換。
   * Servlet命名要規範,因為該方法不會對 ASCII 字母和數字進行編碼,
   * 也不會對這些 ASCII 標點符號進行編碼: - _ . ! ~ * ' ( )
   * 如果 URI 元件中含有分隔符,比如 ? 和 #,則使用 encodeURIComponent() 方法對各元件編碼。
   */

    this.url =  encodeURI(url);
    xmlObj.onreadystatechange = callback;
    xmlObj.open("POST", url, true);
    // 若向html表單那樣POST請求
    xmlObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded;");
    xmlObj.send(str);
 }

// 事件處理函式
function doPost(url, str, elem) {
    var reqObj = XHRObj();
    this.str = str;
    this.elem = elem;
    function ajaxCallback() {
        if (reqObj.readyState == 4) {
            if (reqObj.status == 200) {
                var content = reqObj.responseText;
                elem.innerHTML = content;
            }
        }
    }
    loadReq(reqObj, url, ajaxCallback, str);
}

Servlet

package com;

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 NewServlet extends HttpServlet {

/**
  * 
  */
private static final long serialVersionUID = 1L;


/**
  * Constructor of the object.
  */
public NewServlet() {
    super();
}


/**
  * Destruction of the servlet. <br>
  */
public void destroy() {
    super.destroy(); // Just puts "destroy" string in log
    // Put your code here
}



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


public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        // 請求中文亂碼處理
        request.setCharacterEncoding("UTF-8");

        // 響應中文亂碼  位元組流處理
        response.setHeader("Content-Type","text/html;application/json;charset=UTF-8");

        //響應中文亂碼  字元流處理;設定response緩衝區編碼
        response.setContentType("text/html;charset=UTF-8");
        response.setContentType("text/html");  
        response.setHeader("Cache-Control", "no-store");  
        response.setHeader("Pragma", "no-cache");  
        response.setDateHeader("Expires", 0);

        PrintWriter out = response.getWriter();

        //接收引數
        String username = request.getParameter("username");
        System.out.println("username = " + username);
        String info = "";
        System.out.println(info);

        out.println(username);
        out.println(info);

        out.close();
}

/**
  * Initialization of the servlet. <br>
  * 
  * @throws ServletException
  *             if an error occurs
  */
public void init() throws ServletException {
   // Put your code here
}

}

web.xml 配置

<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>NewServlet</servlet-name>
    <servlet-class>com.NewServlet</servlet-class>
</servlet>
<!--Servlet 地址對映 -->
<servlet-mapping>
    <servlet-name>NewServlet</servlet-name>
    <url-pattern>/servlet/NewServlet</url-pattern>
</servlet-mapping>