Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

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

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

<form method="post">
    <button id="button_1" value="val_1" name="but1">button 1</button>
    <button id="button_2" value="val_2" name="but2">button 2</button>
    <input id="access_token" type="hidden" name="access_token" value="<?php echo $_SESSION['access_token']; ?>" />
</form>
$(document).ready(function() {
  $("#button_1").click(function(e) {
    e.preventDefault();
    $.ajax({
      type: "POST",
      url: "/pages/test/",
      data: {
        id: $("#button_1").val(),
        access_token: $("#access_token").val()
      },
      success: function(result) {
        alert('ok');
      },
      error: function(result) {
        alert('error');
      }
    });
  });

  $("#button_2").click(function(e) {
    e.preventDefault();
    $.ajax({
      type: "POST",
      url: "/pages/test/",
      data: {
        id: $("#button_2").val(),
        access_token: $("#access_token").val()
      },
      success: function(result) {
        alert('ok');
      },
      error: function(result) {
        alert('error');
      }
    });
  });
});

How can I improve this code and maybe merge it into one function?

question from:https://stackoverflow.com/questions/35203019/how-can-i-send-an-ajax-request-on-button-click-from-a-form-with-2-buttons

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');
        }
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...