如何将表单id或提交按钮传递到ajax


How to pass the form id or submit button into ajax

这是我的index.php

$('#searchAdv').click(function() {
  //What to be put here            
  $.ajax({
    //what to be put here
    url:"filter.php",
    success: function(response){
      $('#view').html(response);
    }              
  });
});

<form>
  <select id="adv1" name="task1">
     <option value="blabla">Bla Bla</option>
     .
     .
     .
  </select>
  <select id="adv2" name="task2">
     <option value="blabla">Bla Bla</option>
     .
     .
     .
  </select>
  <input type="submit" id="searchAdv" value="Filter">
</form>
<div id="view"></div>

如何将表单id或提交按钮传递到ajax,以便将表单内容发送到另一个php页面

首先,您没有表单的id。所以加上…

<form id="myForm">

那么我相信你的问题将得到解决,如果你只是绑定到提交调用表单,而不绑定点击提交按钮。

$( "#myForm" ).submit(function( event ) {
  // use ajax call in here, this will now refer to your form
  var serialized = $(this).serialize();
});

你可以保留点击绑定,但这对我来说不太常见。然后,您只需在当前函数中使用$("#myForm")选择器访问表单。

你可以这样做:

 <form>
 <select id="adv1" name="task1">
 <option value="blabla">Bla Bla</option>
 .
 .
 .
</select>
<select id="adv2" name="task2">
 <option value="blabla">Bla Bla</option>
 .
 .
 .
</select>
<input type="submit" onclick="add()" >
</form>

,然后你的ajax必须添加数据类型和数据(你的数据),像这样:

function add(){
  var username = $("#adv1").val();
  var password = $("#adv2").val();
  $.ajax({
    dataType: 'html',
    url: "filter.php>",
    type: "POST",
    data: username+password,
  }).done(function(data) {
    $('#view').html(response);
  });
}

您可以使用jQuery的submit事件处理程序在提交表单时捕获字段值,然后将它们发送给ajax方法。但首先需要将id附加到表单上。假设我们保留一个id="form"

$('#form').on('submit',function(){
    method = $(this).attr('method');
    url = $(this).attr('action');
/*define these attributes in your form. Here you grab them and pass them to the ajax method later.*/
/* next you want the values of all your input fields.
 * So we grab them values and assign them to their respective name attributes
 * and we put the whole thing in the data object which we will send via ajax.
 * It will look something like:
   { name_attribute_of_a_field:"value of that field",
     name_attribute_of_another_field:"value of that field",
     ..and so on}
 */
    data = {};
    $(this).find('[name]').each(function(){  
    /*this will find all elements with a name attribute in it and loop through each of them.*/
        name = $(this).attr('name');
        value = $(this).val();
        data[name] = value;
    });
    $.ajax({
        url:url,
        method:method,
        data:data,
        datatype:"type-of-response-data you expect",
        success: function(data){
            $('#view').html(data);
        }
    });
});