JavaScript—異步提交表單的6種方式

在學習異步提交表單之前,先來學習幾個JQuery方法和屬性。

1、serialize():序列表格內容爲字符串。如下:

queryBean.orderBy=OPERATE_TIME&queryBean.orderSequnce=DESC&queryBean.title=&queryBean.province=&queryBean.city=&selectID=ad78f509f2bc412fb9fe16e36d227a11&queryBean.orderBy=OPERATE_TIME&queryBean.orderSequnce=DESC&queryBean.page.intPage=1

2、serializeArray():序列化表格元素 (類似 ‘.serialize()’ 方法) 返回 JSON 數據結構數據。

注意,此方法返回的是JSON對象而非JSON字符串。需要使用插件或者第三方庫進行字符串化操作。

返回的JSON對象是由一個對象數組組成的,其中每個對象包含一個或兩個名值對——name參數和value參數(如果value不爲空的話)。舉例來說:

[
    {
        "name": "firstname", 
        "value": "Hello"
    }, 
    {
        "name": "lastname", 
        "value": "World"
    }, 
    {
        "name": "alias"
    }
]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

3、data屬性:發送到服務器的數據。將自動轉換爲請求字符串格式。GET 請求中將附加在 URL 後。查看 processData 選項說明以禁止此自動轉換。必須爲 Key/Value 格式。如果爲數組,jQuery 將自動爲不同值對應同一個名稱。如 {foo:[“bar1”, “bar2”]} 轉換爲 “&foo=bar1&foo=bar2”。

4、dataType屬性:預期服務器返回的數據類型。如果不指定,jQuery 將自動根據 HTTP 包 MIME 信息來智能判斷,比如XML MIME類型就被識別爲XML。在1.4中,JSON就會生成一個JavaScript對象,而script則會執行這個腳本。隨後服務器端返回的數據會根據這個值解析後,傳遞給回調函數。可用值:

“xml”: 返回 XML 文檔,可用 jQuery 處理。

“script”: 返回純文本 JavaScript 代碼。不會自動緩存結果。除非設置了”cache”參數。”’注意:”’在遠程請求時(不在同一個域下),所有POST請求都將轉爲GET請求。(因爲將使用DOM的script標籤來加載)。

“json”: 返回 JSON 數據 。

“jsonp”: JSONP 格式。使用 JSONP 形式調用函數時,如 “myurl?callback=?” jQuery 將自動替換 ? 爲正確的函數名,以執行回調函數。

“text”: 返回純文本字符串

一、ajax方式

<script type="text/javaScript">
    $.ajax({
        url:"mobileSurveyAction_addSurvey.action",//提交地址
        data:$("#form1").serialize(),//將表單數據序列化
        type:"POST",
        dataType:"json",
        success:function(result){
            if (result.success == '100'){
                $("#mySection").hide();
                $(".footer").hide();
                $("#alertMsg").show();
            }else{
                alert("失敗!");
            }
        }
    });
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

二、submit方式

有時在A頁面點擊按鈕彈出一個form表單,在填完表單後提交成功後,需要關閉表單頁並將表單中的某些值反應在A頁面上,這時就需要異步提交表單。其實也挺簡單,只是需要把表單數據序列化。

<script type="text/javaScript">
    $("#form1").submit(function (){ 
        var ajax_url = "yourActionUrl"; //表單目標 
        var ajax_type = $(this).attr('method'); //提交方法 
        var ajax_data = $(this).serialize(); //表單數據 

        $.ajax({ 
             type:ajax_type, //表單提交類型 
             url:ajax_url, //表單提交目標 
             data:ajax_data, //表單數據
             success:function(msg){
                  if(msg == 'success'){//msg 是後臺調用action時,你傳過來的參數
                       //do things here
                       window.close();
                  }else{
                       //do things here
                  }
             } 
        }); 
        //return false; //阻止表單的默認提交事件 
    });
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

三、submit方式2

<html>
<head>
<script type="text/javaScript">
    jQuery(document).ready(function (){
       jQuery('#search_form').bind("submit", function(){
                   var key_word = jQuery("#keyword").val();
                   if(key_word == ""){ 
                     return false; 
                  }
                   var options = {
                              url: '/portrait/user_info_display?user_info_keyword=' + key_word,
                              type: 'post',
                              dataType: 'text',
                              data: $("#search_form").serialize(),
                              success: function (data) {
                                    if (data.length > 0){
                                        jQuery("#user_info").html(data);
                                    }
                              }
                   };
                   $.ajax(options);
                   return false;
            });

     $('#search').click(function(){
            $('#search_form').submit();
         });
  });
</script>
</head>
<body>
    <form mothod="post" id="search_form">
        <div class="cf">
            <label class="search-bar">
                <input id="keyword" placeholder="請輸入搜索關鍵詞" name="user_info_keyword" type="text" value="" class="input-search">
                <a id="search" class="btn-search">
                    <i class="icon-search"></i>
                </a>
                <a href="javascript:;" class="btn-more"></a>
            </label>
        </div>
    </form>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

代碼完成了兩個功能:1.輸入關鍵詞後按回車,會向server發送一個POST請求,然後異步提交表單,刷新部分頁面;2.輸入關鍵詞後,點擊查詢按鈕,也可異步刷新部分頁面。

此時要注意表單提交後發送的是POST請求,而點擊按鈕會發送一個GET請求,所以我們可以通過jQuery,使得按鈕點擊時觸發表單提交,這樣後端就不用再寫代碼處理GET請求。

四、隱藏的iframe模擬異步上傳

爲什麼在這裏說的是模擬呢?因爲我們其實是將返回結果放在了一個隱藏的iframe中,所以纔沒有使當前頁面跳轉,感覺就像是異步操作一樣。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta charset="UTF-">
<title>隱藏的iframe上傳文件</title>
<script type="text/javascript" src="jquery路徑..."></script>
</head>
<body>
    <iframe name="frm" style="display: none"></iframe>
    <form action="/upload" enctype="multipart/form-data" method="post" target="frm" onsubmit="loading(true);">
        <p id="upfile">
            附件: <input type="file" name="myfile" style="display: inline">
        </p>
        <p id="upbtn">
            <input style="padding-left: px; padding-right: px;" type="submit" value="異步上傳">
            <span id="uptxt" style="display: none">正在上傳...</span>
        </p>
    </form>
    <div id="flist" style="border: px dotted darkgray;"></div>
    <script>
        // 上傳完成後的回調
        function uploadFinished(fileName) {
            addToFlist(fileName);
            loading(false);
        }

        function addToFlist(fname) {
            var temp = ["<p id='" + fname + "'>",fname,"<button οnclick='delFile(\""+fname+"\");'>刪除</button>","</p>"];
            $("#flist").append(temp.join(""));
        }

        function loading(showloading) {
            if (showloading) {
                $("#uptxt").show();
            } else {
                $("#uptxt").hide();
            }
        }
    </script>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

這種技術有兩個關鍵的地方:

  1. form會指定target,提交的結果定向返回到隱藏的ifram中。(即form的target與iframe的name屬性一致)。
  2. 提交完成後,iframe中頁面與主頁面通信,通知上傳結果及服務端文件信息.

如何與主頁面通信呢? 
  我們用nodejs在接收完了文件後返回了一個window.parent.主頁面定義的方法,執行後可以得知文件上傳完成。代碼很簡單:

router.post('/upload', multipartMiddleware, function(req, res) {
    var fpath = req.files.myfile.path;
    var fname = fpath.substr(fpath.lastIndexOf('\\') + );
    setTimeout(function() {
        var ret = ["<script>","window.parent.uploadFinished('"+fname+"');","</script>"];
        res.send(ret.join(""));
    }, );
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

五、使用XMLHttpRequest2來進行真正的異步上傳

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-">
<title>xhr level 異步上傳</title>
<script type="text/javascript" src="jquery路徑..."></script>
</head>
<body>
<div>
    <p id="upfile">
        附件: <input type="file" id="myfile" style="display: inline">
    </p>
    <p id="upbtn">
        <input style="padding-left: px; padding-right: px;" type="button" value="異步上傳" onclick="upload();">
        <span id="uptxt" style="display: none">正在上傳...</span>
        <span id="upprog"></span>
        <button id="stopbtn" style="display: none;">停止上傳</button>
    </p>
</div>
<div id="flist" style="border: px dotted darkgray;"></div>

<script>
function upload() {
    // 準備FormData
    var fd = new FormData();
    fd.append("myfile", $("#myfile")[0].files[0]);

    // 創建xhr對象
    var xhr = new XMLHttpRequest();
    // 監聽狀態,實時響應
    // xhr 和 xhr.upload 都有progress事件,xhr.progress是下載進度,xhr.upload.progress是上傳進度
    xhr.upload.onprogress = function(event) {
        if (event.lengthComputable) {
            var percent = Math.round(event.loaded / event.total);
            console.log('%d%', percent);
            $("#upprog").text(percent);
        }
    };
    // 傳輸開始事件
    xhr.onloadstart = function(event) {
        console.log('load start');
        $("#upprog").text('開始上傳');

        $("#stopbtn").one('click', function() {
            xhr.abort();
            $(this).hide();
        });

        loading(true);
    };
    // ajax過程成功完成事件
    xhr.onload = function(event) {
        console.log('load success');
        $("#upprog").text('上傳成功');

        console.log(xhr.responseText);
        var ret = JSON.parse(xhr.responseText);
        addToFlist(ret.fname);
    };
    // ajax過程發生錯誤事件
    xhr.onerror = function(event) {
        console.log('error');
        $("#upprog").text('發生錯誤');
    };
    // ajax被取消
    xhr.onabort = function(event) {
        console.log('abort');
        $("#upprog").text('操作被取消');
    };
    // loadend傳輸結束,不管成功失敗都會被觸發
    xhr.onloadend = function (event) {
        console.log('load end');
        loading(false);
    };
    // 發起ajax請求傳送數據
    xhr.open('POST', '/upload', true);
    xhr.send(fd);
}
function addToFlist(fname) {
    var temp = ["<p id='" + fname + "'>",fname,"<button οnclick='delFile(\"" + fname + "\");'>刪除</button>","</p>"];
    $("#flist").append(temp.join(""));
}
function delFile(fname) {
    console.log('to delete file: ' + fname);
    // TODO: 請實現
}
function loading(showloading) {
    if (showloading) {
        $("#uptxt").show();
        $("#stopbtn").show();
    } else {
        $("#uptxt").hide();
        $("#stopbtn").hide();
    }
}
</script>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98

  代碼有點多,但是通俗易懂。使用過AJAX的人都知道,XHR對象提供了一個onreadystatechange的回調方法來監聽整個請求/響應過程。在XMLHttpRequest2級規範中又多了幾個進度事件。有以下6個事件: 
  1.loadstart: 在接收到響應數據的第一個字節時觸發。 
  2.progress: 在接收響應期間持續不斷地觸發。 
  3.error: 在請求發生錯誤時觸發。 
  4.abort: 在因爲調用abort()方法而終止連接時觸發。 
  5.load: 在接收到完整的響應數據時觸發。 
  6.loadend: 在通信完成或者觸發error,abort,load事件後觸發。 
   
  這次我們可以解讀代碼:當傳輸事件開始後,我們便在停止傳送按鈕上添加點擊事件,內置了abort方法可以停止傳送。若不點則會正常上傳直到傳送完畢爲止。其後臺代碼類似第二種方法。

六、使用jQuery和FormData來進行異步上傳

FormData的詳細介紹及使用請點擊此處,那裏對FormData的方法和事件已經表述的非常清楚,這裏就不再浪費時間在介紹一遍了。本文主要針對FormData對象的使用以及異步文件上傳進行詳細的說明。

FormData對象可以讓我們組織一個使用XMLHttpRequest對象發送的鍵值對的集合。它主要用於發送表單數據,但是可以獨立於使用表單傳輸的數據。

1、從頭開始創建一個FormData對象

你可以創建一個你自己的FormData對象,然後通過append() 方法向對象中添加鍵值對,就像下面這樣:

var formData = new FormData();

formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"

// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);

// JavaScript file-like object
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

formData.append("webmasterfile", blob);

var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

注意:字段”userfile” 和 “webmasterfile” 都包含文件(file)。被分配到字段”accountnum”上的數字直接被FormData.append()方法轉換成了字符串(字段的值(value)可能是一個Blob, File, 或一個string:如果值既不是Blob也不是File,則值會被轉換成一個string)。

這個例子創建了一個FormData實例,其中包含字段”username”, “accountnum”, “userfile” 和 “webmasterfile”,然後使用XMLHttpRequest對象的send()方法去發送表單數據。字段”webmasterfile”是一個Blob。一個Blob對象代表一個文件對象的原始數據。但是Blob代表的數據不必須是javascript原生格式的數據。文件接口是基於Blob,繼承Blob功能和擴大它對用戶文件系統的支持。爲了構建一個Blob可以調用Blob()構造函數。

2、從一個HTML表單獲得一個FormData對象

爲了獲得一個包含已存在表單數據的FormData對象,在創建FormData對象的時候需要指定表單元素。

var formData = new FormData(someFormElement);
  • 1

就像下面這樣:

var formElement = document.querySelector("form");
var request = new XMLHttpRequest();
request.open("POST", "submitform.php");
request.send(new FormData(formElement));
  • 1
  • 2
  • 3
  • 4

你也可以在獲得FormData對象之後增加另外的數據,就像下面這樣:

var formElement = document.querySelector("form");
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "submitform.php");
formData.append("serialnumber", serialNumber++);
request.send(formData);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

這樣你可以在發送之前增加額外的信息,不一定是用戶編輯的。

3、使用FormData對象發送文件

你可以使用FormData發送文件。簡單的<form>中在包含一個<input>元素就可以:

<form enctype="multipart/form-data" method="post" name="fileinfo">
  <label>Your email address:</label>
  <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
  <label>Custom file label:</label>
  <input type="text" name="filelabel" size="12" maxlength="32" /><br />
  <label>File to stash:</label>
  <input type="file" name="file" required />
  <input type="submit" value="Stash the file!" />
</form>
<div></div>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

然後你可以使用下面的代碼去發送:

var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {

  var oOutput = document.querySelector("div"),
      oData = new FormData(form);

  oData.append("CustomField", "This is some extra data");

  var oReq = new XMLHttpRequest();
  oReq.open("POST", "stash.php", true);
  oReq.onload = function(oEvent) {
    if (oReq.status == 200) {
      oOutput.innerHTML = "Uploaded!";
    } else {
      oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
    }
  };

  oReq.send(oData);
  ev.preventDefault();
}, false);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

你也可以直接向FormData對象中添加File或Blob,就像下面這樣:

data.append("myfile", myBlob, "filename.txt");
  • 1

當使用append() 方法的時候,可能會使用到第三個參數去發送文件名稱(通過Content-Disposition頭髮送到服務器)。如果沒有指定第三個參數或這個參數不被支持的話,第三個參數默認是”blob”。

如果你設置好正確的options,你也可以和jQuery配合起來使用:

var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
  url: "stash.php",
  type: "POST",
  data: fd,
  processData: false,  // tell jQuery not to process the data
  contentType: false   // tell jQuery not to set contentType
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

發佈了101 篇原創文章 · 獲贊 66 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章