4

$.ajaxjQuery Forms Plugin を使用してフォームを送信するための使用をリファクタリングしています。APIは、に渡され$.ajaxた任意のオプションを に渡すことができると述べています$.ajaxSubmitbeforeSubmitのオプション オブジェクトを変更して、プロパティを追加したいと考えていdataます。options.beforeSubmitinの値を警告するprocessSubmitことは、これがハンドラーによって初期化されたオプション オブジェクトであり、データが設定されていることを示唆していますが、オプション オブジェクトはプロパティなしで既に初期化されているdataため、サーバーに送信される投稿には含まれません。beforeSubmitまたはその他の方法でオプション オブジェクトを変更することはできますか?

ドキュメントの準備ができたら、ハンドラーを次のようにバインドしsubmit()ます。

$("#myform").submit(function() {
    var options = { dataType: 'json',
            beforeSubmit: processSubmit,
            success: endSubmit };
    $(this).ajaxSubmit(options);
    return false;
});

このprocessSubmit(arr, $form, options)関数は、JSON としてサーバーに送信されるデータをパッケージ化します。

function processSubmit(arr, $form, options) {
    var followers =[];
    $($("#follower-multi-select").children().filter("li")).each(function() {
      if ($(this).hasClass("selected")) {
        var fwr =  $(this).attr("id");
        followers.push(fwr);
      }
    });

    var postData = { followers : followers };
    alert('beforeSubmit is: ' + options.beforeSubmit);

    options.data = 'json='+$.toJSON(postData);
    alert('data set: ' + options.data);
}

フォーム HTML:

<form id="myform" action="/myaction" method="post">
    <fieldset>
        <legend>Choose your competitors</legend>
        <ul id="follower-multi-select" class="follower-multi-select">
            {% for f in follower_thumbs %}
            <li id="{{ f.hashedkey }}"><img src='{{ f.thumb }}' alt="{{ f.name }}" /><span class="name-multi-select">{{ f.name }}</span></li>
            {% endfor %}
        </ul>
    </fieldset>
    <input id="send" type="submit" class="large" value="send" />
</form>
4

1 に答える 1

3

代わりにオプションbeforeSubmitを使用する必要があるためbeforeSerialize、シリアル化されたときにデータが含まれます。.dataに渡されたオプションを設定しているのではなく、シリアル化するときに含める追加データのプラグインのプロパティであるオプションを$.ajax()設定.dataしています。$.ajaxSubmit()発生したbeforeSubmit場合、シリアル化は既に完了しているため、次のように、その前に介入する必要があります。

$("#myform").submit(function() {
    var options = { dataType: 'json',
            beforeSerialize: processSubmit,
            success: endSubmit };
    $(this).ajaxSubmit(options);
    return false;
});

function processSubmit($form, options) {
    var followers = $("#follower-multi-select > li.selected").map(function() {
        return this.id;
    }).get();

    var postData = { followers : followers };
    alert('beforeSubmit is: ' + options.beforeSubmit);

    options.data = 'json='+$.toJSON(postData);
    alert('data set: ' + options.data);
}

ここでも子セレクターを使用.map()して、配列の取得をより簡単にしましたが、元のメソッドは機能します... からのコールバックでパラメーターが異なるという重要な違いに注意してください。コールバックのパラメーターはありません。>beforeSubmitarrbeforeSerialize

于 2010-07-08T10:38:40.510 に答える