How can I send an Ajax Request on button click from a form with 2 buttons?

后端 未结 3 1051
-上瘾入骨i
-上瘾入骨i 2020-12-13 18:09

I want to send a request from one page to another from a form which has 2 buttons:

相关标签:
3条回答
  • 2020-12-13 18:35

    Given that the only logical difference between the handlers is the value of the button clicked, you can use the this keyword to refer to the element which raised the event and get the val() from that. Try this:

    $("button").click(function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "/pages/test/",
            data: { 
                id: $(this).val(), // < note use of 'this' here
                access_token: $("#access_token").val() 
            },
            success: function(result) {
                alert('ok');
            },
            error: function(result) {
                alert('error');
            }
        });
    });
    
    0 讨论(0)
  • 2020-12-13 18:42
    function sendAjaxRequest(element,urlToSend) {
                 var clickedButton = element;
                  $.ajax({type: "POST",
                      url: urlToSend,
                      data: { id: clickedButton.val(), access_token: $("#access_token").val() },
                      success:function(result){
                        alert('ok');
                      },
                     error:function(result)
                      {
                      alert('error');
                     }
                 });
         }
    
           $(document).ready(function(){
              $("#button_1").click(function(e){
                  e.preventDefault();
                  sendAjaxRequest($(this),'/pages/test/');
              });
    
              $("#button_2").click(function(e){
                  e.preventDefault();
                  sendAjaxRequest($(this),'/pages/test/');
              });
            });
    
    1. created as separate function for sending the ajax request.
    2. Kept second parameter as URL because in future you want to send data to different URL
    0 讨论(0)
  • Use jQuery multiple-selector if the only difference between the two functions is the value of the button being triggered.

    $("#button_1, #button_2").on("click", function(e) {
        e.preventDefault();
        $.ajax({type: "POST",
            url: "/pages/test/",
            data: { id: $(this).val(), access_token: $("#access_token").val() },
            success:function(result) {
              alert('ok');
            },
            error:function(result) {
              alert('error');
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题