如何将表单ID或提交按钮传递给ajax

时间:2016-09-17 15:04:54

标签: php 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页面

3 个答案:

答案 0 :(得分:0)

首先,您没有表单的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")选择器访问表单。

答案 1 :(得分:0)

你可以像这样做altenative:

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

答案 2 :(得分:-1)

您可以使用jQuery的提交事件处理程序在提交表单时捕获字段值,然后将它们发送到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);
        }
    });
});
相关问题