【jQuery】使用jquery.form.js,獲取提交表單返回值

jQuery表單庫介紹

實現 html 中提交表單並實現不跳轉頁面處理返回值

jQuery表單庫(jquery.form.js庫)以jQuery爲基礎,用於處理表單AJAX提交,使得表單AJAX提交簡單、容易,且能完整控制提交過程和處理結果,不需要任何特殊標籤輔助,不影響原表單結構,只要使用該庫就能使普通表單平滑升級爲ajax提交表單。

官方地址:https://github.com/jquery-form/form

源代碼查看和下載地址:https://github.com/jquery-form/form/blob/master/src/jquery.form.js

AjaxForm使用示例

1、導入js文件

需要導入相關的js文件。使用ajaxForm方式需要使用到jquery和jquery-form兩個js文件。如:

    <script type="text/javascript" src="/static/js/jquery-1.7.2.js"></script>
    <script type="text/javascript" src="/static/js/jquery.form.min.js"></script>

2、綁定表單

表單綁定它一般在$(document).ready(function () {}裏定義,它能讓表單不刷新頁面的情況下POST到目標。如:

表單示例

<form id="editor_form" action="/api/editor/update" method="post">
    <input type="hidden" name="id" value="3"/>
    <input type="submit" value="提交">
</form>

JS示例

 // wait for the DOM to be loaded
 $(document).ready(function () {
     // bind 'myForm' and provide a simple callback function
     $('#editor_form').ajaxForm(function (message) {
         var messageJson = JSON.parse(message);
         if (messageJson.status == '0') {
             alert("保存成功!");
         } else {
             alert("保存失敗,請聯繫管理員!" + message);
         }
     });
 });

3、運行效果

附:官方文檔

Overview

The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process. Both of these methods support numerous options which allows you to have full control over how the data is submitted. Submitting a form with AJAX doesn’t get any easier than this!

1 Add a form to your page. Just a normal form, no special markup required:
<form id="myForm" action="comment.php" method="post">
    Name: <input type="text" name="name" />
    Comment: <textarea name="comment"></textarea>
    <input type="submit" value="Submit Comment" />
</form>
2 Include jQuery and the Form Plugin external script files and a short script to initialize the form when the DOM is ready:
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
    <script src="http://malsup.github.com/jquery.form.js"></script>

    <script>
        // wait for the DOM to be loaded
        $(document).ready(function() {
            // bind 'myForm' and provide a simple callback function
            $('#myForm').ajaxForm(function() {
                alert("Thank you for your comment!");
            });
        });
    </script>
</head>
...

That’s it!

When this form is submitted the name and comment fields will be posted to comment.php. If the server returns a success status then the user will see a “Thank you” message.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章