Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

jQuery 表單提交入門:GET 與 POST 完整示例

這是一個最基礎的 jQuery 非同步提交範例,示範如何用 $.get 與 $.post 把輸入框的值送到後端 Action,並把回應寫回頁面。

前端 JSP

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JQuery 測試頁面</title>
<script type="text/javascript">
    function verify(){
        var jqueryObj = $("#username");
        //獲取節點的值
        var userName = jqueryObj.val();
        alert(userName);
        $.get("TestAction!test.action?name=" + userName, null, callback);
    }
    function callback(data){
        var resultObj = $("#result");
        resultObj.html(data);
    }
    function postsubmit(){
        $.post("TestAction!test.action?name=" + $("#username").val(), null, callback);
    }
    function clean(){
        var resultObj = $("#result");
        resultObj.html("");
    }
</script>
</head>
<body>
    <h1>JQuery 練習</h1>
    <input id="username" name="username" value="請輸入..."></input>
    <input type="button" onclick="verify()" value="確定"/>
    <input type="button" onclick="postsubmit()" value="post 提交"/>
    <input type="button" onclick="clean()" value="清除"/>
    <div id="result"/>
</body>
</html>

後端 Action

package com.xiaoqiang;

import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class TestAction extends ActionSupport {
    private String name;

    @Override
    public String execute() throws Exception {
        return "test";
    }

    public void test() throws Exception {
        System.out.println("name:" + new String(name.getBytes("iso-8859-1"), "utf-8"));
        HttpServletResponse httpServletResponse = ServletActionContext.getResponse();
        httpServletResponse.setContentType("text/html;charset=utf-8");
        PrintWriter pw = httpServletResponse.getWriter();
        pw.print("可以注冊");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

範例中的 callback 是共用的回呼函式,GET 與 POST 兩種提交方式都會把伺服器回傳的字串插入 #result 這個 div。實務上若要處理中文,後端需留意編碼轉換,示範中是以 iso-8859-1 解碼再轉成 UTF-8。

Copyright © Linux教程網 All Rights Reserved