在jQuery Ajax函數中傳遞整個表單作為數據。

[英]Pass entire form as data in jQuery Ajax function


I have a jQuery ajax function and would like to an entire form as post data. We are constantly updating the form so it becomes tedious to constantly update the form inputs that should be sent in the query.

我有一個jQuery ajax函數,並希望將整個表單作為post數據。我們不斷更新表單,因此不斷更新應該在查詢中發送的表單輸入變得單調乏味。

7 个解决方案

#1


230  

There's a function that does exactly this:

有一個函數就是這樣的:

http://api.jquery.com/serialize/

http://api.jquery.com/serialize/

var data = $('form').serialize();
$.post('url', data);

#2


28  

serialize() is not a good idea if you want to send a form with post method. For example if you want to pass a file via ajax its not gonna work.

如果您想用post方法發送表單,那么序列化()不是一個好主意。例如,如果您想通過ajax傳遞一個文件,那么它將無法工作。

the better solution is to make a FormData and send it:

更好的解決方案是創建一個FormData並發送它:

    var myform = document.getElementById("myform");
    var fd = new FormData(myform );
    $.ajax({
        url: "example.php",
        data: fd,
        cache: false,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (dataofconfirm) {
            // do something with the result
        }
    });

#3


23  

In general use serialize() on the form element.

通常,在表單元素上使用serialize()。

Please be mindful that multiple <select> options are serialized under the same key, e.g.

請注意,多個

<select id="foo" name="foo" multiple="multiple">
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
</select>

will result in a query string that includes multiple occurences of the same query parameter:

將產生一個查詢字符串,其中包含相同查詢參數的多個事件:

[path]?foo=1&foo=2&foo=3&someotherparams...

which may not be what you want in the backend.

這可能不是你在后端想要的。

I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):

我使用這個JS代碼將多個參數減少到一個逗號分隔的單個密鑰(在John Resig的一個線程中,從一個評論者的響應中,從一個評論者的響應中完全復制):

function compress(data) {
    data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
    return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}

which turns the above into:

將上述內容轉化為:

[path]?foo=1,2,3&someotherparams...

In your JS code you'd call it like this:

在你的JS代碼中,你會這樣稱呼它:

var inputs = compress($("#your-form").serialize());

Hope that helps.

希望有幫助。

#4


14  

Use

使用

serialize( )

serialize()

var str = $("form").serialize();

Serialize a form to a query string, that could be sent to a server in an Ajax request.

將表單序列化為查詢字符串,可以在Ajax請求中發送給服務器。

#5


0  

A good jQuery option to do this is through FormData. This method is also suited when sending files through a form!

一個好的jQuery選項是通過FormData實現的。這種方法也適用於通過表單發送文件!

<form id='test' method='post' enctype='multipart/form-data'>
   <input type='text' name='testinput' id='testinput'>
   <button type='submit'>submit</button>
</form>

Your send function in jQuery would look like this:

在jQuery中發送函數是這樣的:

$( 'form#test' ).submit( function(){
   var data = new FormData( $( 'form#test' )[ 0 ] );

   $.ajax( {
      processData: false,
      contentType: false,

      data: data,
      dataType: 'json',
      type: $( this ).attr( 'method' );
      url: 'yourapi.php',
      success: function( feedback ){
         console.log( "the feedback from your API: " + feedback );
      }
});

to add data to your form you can either use a hidden input in your form, or you add it on the fly:

要將數據添加到表單中,您可以使用表單中的隱藏輸入,或者將其添加到飛行中:

var data = new FormData( $( 'form#test' )[ 0 ] );
data.append( 'command', 'value_for_command' );

#6


0  

You just have to post the data. and Using jquery ajax function set parameters. Here is an example.

你只需要發布數據。並使用jquery ajax函數設置參數。這是一個例子。

<script>
        $(function () {

            $('form').on('submit', function (e) {

                e.preventDefault();

                $.ajax({
                    type: 'post',
                    url: 'your_complete url',
                    data: $('form').serialize(),
                    success: function (response) {
                        //$('form')[0].reset();
                       // $("#feedback").text(response);
                        if(response=="True") {
                            $('form')[0].reset();
                            $("#feedback").text("Your information has been stored.");
                        }
                        else
                            $("#feedback").text(" Some Error has occured Errror !!! ID duplicate");
                    }
                });

            });

        });
    </script>

#7


-1  

<form id="add-item-form">
    . . .
</form>   

<script>
    $('#add-item-form').submit(function (event) {
        event.preventDefault();
        var data = $('#add-item-form').serialize();
        $.post("/Item/AddItem", data, function (response) {
            . . .
        });
    });
</script>

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/01/07/dc42a771f8c95ac7fa745d3d85da7b13.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com