如何从带有2个按钮的表单上单击按钮发送Ajax请求? [英] How can I send an Ajax Request on button click from a form with 2 buttons?

查看:339
本文介绍了如何从带有2个按钮的表单上单击按钮发送Ajax请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,抱歉这里有点通用的问题。我是Ajax的新手,想要从一个有两个按钮的表单将一个页面的请求发送到另一个页面。

Hi all and sorry for a bit generic question here. I'm new to Ajax and 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');
      }
    });
  });
});

有任何人有任何建议如何改进此代码并可能将其合并为一个函数或其他东西?

Has any one got any suggestions how I can improve this code and maybe merge it into one function or something?

提前致谢! :)

推荐答案

鉴于处理程序之间唯一的逻辑差异是单击按钮的值,您可以使用这个关键字引用引发事件的元素并从中获取 val()。试试这个:

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

这篇关于如何从带有2个按钮的表单上单击按钮发送Ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆