1

送信時に特定のページに移動するフォームがたくさんある PHP Web サイトがあります。したがって、それらは次のようになります。

<form method='post' action='form_target.php'>
    <input type='text' name='fieldname' />
    <button type='submit'/>
</form>

$.post('form-target.php');実際にページを離れることなく、同じことができると思います。しかし、さまざまなフォームの JavaScript コードを作成しないようにしています。

ページ上のフォームを検出し、それらを AJAX 呼び出しに変換する簡単な方法はありますか? たぶん bind onsubmit()、またはonclick();イベントを$.post();呼び出して?

これを実装するための助けもいただければ幸いです。

4

4 に答える 4

4

イベントをすべてのフォームに添付して.submit送信をキャッチ.preventDefault()し、イベントオブジェクトで使用して実際のページ送信を防ぐことができます (ページの変更を停止します)。次に、フォームのデータをシリアル化し (名前と値のペアの文字列を作成)、フォーム要素の action 属性から URL を取得してから、jquery の ajax 関数を呼び出します。

$("form")セレクターの一部として他に何も使用しないと、ページ上のすべてのフォームにこれがアタッチされます

HTML

<form method='post' action='form_target.php'>
    <input type='text' name='fieldname' />
    <button type='submit'/>
</form>

ジャバスクリプト

$("form").submit(function(e){
    e.preventDefault();
    var data = $(this).serialize();
    var url = $(this).attr("action");
    $.ajax({
       url:url,
       type:"POST",
       data:data,
       success:function(){
          //do something when post succedes 
       },
       error:function() {
          // do something when it fails
       }
    });
});

JQuery .ajax

JQuery .serialize

JQuery .submit

これをさらに拡張するには、各フォームが特定の成功メソッドを実行するようにすることができます。これは、特定のフォーム送信に対して特定の何かが必要な場合に役立ちます。

最初に各フォームに data-* 属性を与えます。これを後で送信イベントで使用して、そのフォームの特定の機能をトリガーできます。

<form method='post' action='form_target.php' 
                    data-onerror="nameSubmitError" 
                    data-onsuccess="nameSubmitSuccess">

次に、data-* 属性で指定した 2 つの関数を作成します

function nameSubmitError() {
  //Do some code that will handle the error
}

function nameSubmitSuccess() {
  //Do some code that will handle the success
}

そして .submit イベントで

$("form").submit(function(e){
    e.preventDefault();
    var data = $(this).serialize();
    var url = $(this).attr("action");
    var errorCallback = $(this).data("onerror");
    var successCallback = $(this).data("onsuccess");
    $.ajax({
       url:url,
       type:"POST",
       success:function(){
          //Check that we have a defined function before trying to execute it
          if( typeof(window[successCallback]) == "function" ) {
             //We do have a defined function so execute it
             window[successCallback]();
          }
       },
       error:function() {
          //Check that we have a defined function before trying to execute it
          if( typeof(window[errorCallback]) == "function" ) {
             //We do have a defined function so execute it
             window[errorCallback]();
          }
       }
    });
});

もちろん、すべてのコールバック関数をグローバル空間に配置すると、それが汚染されるため、すべての関数を単一のオブジェクトにセットアップし、代わりにオブジェクト名を使用できます。window

var formCallbacks = {
    nameSubmitError:function() {
      //Do some code that will handle the error
    },
    nameSubmitSuccess: function() {
      //Do some code that will handle the success
    }
};

そして .submit イベントで次のように変更windowしますformCallbacks

//window[errorCallback]();
//Becomes 
formCallbacks[errorCallback]();
于 2013-09-23T20:24:42.863 に答える
1

はい、http://malsup.com/jquery/form/を試すことができます。これは非常に使いやすいです..

<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 submit!"); 
            }); 
        }); 
    </script> 
</head>
<body>
    <form id="myForm" method='post' action='form_target.php'>
       <input type='text' name='fieldname' />
       <button type='submit'/>
    </form>
</body>
</html>
于 2013-09-23T20:22:27.090 に答える
0

次のように実行できます。

$('form').on('submit', function() {
  $.post(
    $(this).prop('action'), // Your url action
    $(this).serialize(),    // Your data
    success: function() {   // Your callback function
      alert('Submitted');
    }
  );
});
于 2013-09-23T20:22:22.973 に答える
0

http://api.jquery.com/submit/

$( "form" ).on( "submit", function( event ) {
    // Your AJAX call
}
于 2013-09-23T20:19:52.903 に答える