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

后端 未结 3 1052
-上瘾入骨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');
            }
        });
    });
    

提交回复
热议问题