首页 > 解决方案 > ajax提交多个变量

问题描述

我刚开始使用 jquery 和 ajax,我猜有一个简单的问题:

我的 html 页面上有一个按钮,如下所示:

<button type="button" id="i" id2="id2" name="name" class="button_red">-</button>

我用 ajax 为 GET-Method 实现了这个 JavaScript 代码:

$('button').click(function(event) {
  event.preventDefault();
  $.ajax({
    type: "GET",
    url: "update_data.php",
    data:  // data here
  });
});

我想要的只是使用 ajax 方法将按钮中的所有变量(如 id、id2、名称、类)发送到我的 update_data.php 文件。我该如何以最好的方式做到这一点?那么我该如何使用.serialize()?

我的想法是:

var id = $(this).attr('id');
var id2 = $(this).attr('id2');
var name = $(this).attr('name');
var array = {id, id2, name};
//
//
//
data: array, array.serialize(),
succcess: ...

非常感谢!

标签: javascriptjquery

解决方案


jQuery AJAX 文档:https ://learn.jquery.com/ajax/jquery-ajax-methods/


你可以发送这个

1) 作为一个object

var DTO = {
  id: $(this).attr('id'),
  id2: $(this).attr('id2'),
  name: $(this).attr('name')
};

2)作为array

var DTO = [
    $(this).attr('id'),  
  $(this).attr('id2'),
  $(this).attr('name')
];

推荐阅读