簡體   English   中英

通過ajax通過一個按鈕將單個表單提交給兩個操作

[英]Submit single form to two actions with one button via ajax

在下面的代碼中,您可以看到'$ _SERVER ['REQUEST_URI']''ContactCreate.php',這是我需要將單個表單發送到的兩個操作。 我不確定如何才能使它正常工作。

謝謝大家

$(function() {
    $("#myform").on("submit", function(e) {
        e.preventDefault();
        $.ajax({
            url: '$_SERVER['REQUEST_URI']'  'ContactCreate.php',
            type: 'POST',
            data: $(this).serialize(),
            beforeSend: function() {
                $("#message").html("sending...");
            },
            success: function(data) {
                $("#message").hide();
                $("#response").html(data);
            }
        });
    });
});

您將需要2個Ajax調用。 您可以等待兩者都完成$.when方法的使用並在那里執行通用邏輯

 $(function() {
    $("#myform").on("submit", function(e) {
        e.preventDefault();
        $("#message").html("sending...");

        var formSerialized = $(this).serialize();

        var ajaxCall1 = $.post('$_SERVER['REQUEST_URI']', formSerialized);
        var ajaxCall2 = $.post('ContactCreate.php', formSerialized);

        $.when( ajaxCall1, ajaxCall2).done(function (v1, v2) {
            $("#message").hide();
            // your logic when both ajax request finished   
        });     
    });
});

同樣不確定$_SERVER['REQUEST_URI']是否可以解析為Javascript上的任何內容,這取決於此代碼的放置位置。

只需將其彼此相鄰添加即可:

$(function() {
  $("#myform").on("submit", function(e) {
    e.preventDefault();
    $.ajax({
      url: '<?php echo $_SERVER['REQUEST_URI']; ?>' ,
      type: 'POST',
      data: $(this).serialize(),
      beforeSend: function() {
        $("#message").html("sending...");
      },
      success: function(data) {
        $("#message").hide();
        $("#response").html(data);
      }
    });
    $.ajax({
      url:  'ContactCreate.php',
      type: 'POST',
      data: $(this).serialize(),
      beforeSend: function() {
        $("#message").html("sending...");
      },
      success: function(data) {
        $("#message").hide();
        $("#response").html(data);
      }
    });
  });
});

您必須使用REQUEST_URI的JS類似物

var request_uri = location.pathname + location.search;

在您的代碼上-

  $(function() { $("#myform").on("submit", function(e) { e.preventDefault(); $.ajax({ url: location.pathname + location.search+ 'ContactCreate.php', type: 'POST', data: $(this).serialize(), beforeSend: function() { $("#message").html("sending..."); }, success: function(data) { $("#message").hide(); $("#response").html(data); } }); }); }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM