使用Ajax在下拉列表更改时提交表单

时间:2012-12-19 17:37:51

标签: jquery ajax

我有以下内容调用另一个文件并根据下拉值吐出输出。它工作正常,但没有提交按钮我似乎无法正常工作。这有效,除非它将自己重定向到process.php并输出正确的值。此代码的重点是在空div(output)中显示输出。

$(document).ready(function() {
   $('#dropdown').change( function() {
       $('#myform').submit();
       $.ajax({ // create an AJAX call...
           data: $(this).serialize(), // get the form data
           type: $(this).attr('method'), // GET or POST
           url: $(this).attr('action'), // the file to call
           success: function(response) { // on success..
               $('#output').html(response); // update the DIV
           }
       });
       return false; // cancel original event to prevent form submitting
    });
});


<form id="myform" method=POST action="process.php">
<select id="dropdown" name="dropdown">
    <option value="QU">QU</option>
    <option value="QF">QF</option>
    <option value="QC">QC</option>
</select>
</form>
<div id="output"></div>

3 个答案:

答案 0 :(得分:6)

如果您想使用ajax,请不要提交表单,同样在下拉列表更改事件中this是下拉元素而不是表单。

$(document).ready(function() {
   $('#dropdown').change( function() {
       $.ajax({ // create an AJAX call...
           data: $('#myform').serialize(), // serialize the form
           type: $('#myform').attr('method'), // GET or POST from the form
           url: $('#myform').attr('action'), // the file to call from the form
           success: function(response) { // on success..
               $('#output').html(response); // update the DIV
           }
       });
    });
});

答案 1 :(得分:5)

我认为JQuery加载函数可以在更少的代码中完成您的工作。

$(document).ready(function() {
   $('#dropdown').change( function() {

    $('#output').load('/process.php',{dropdown: $(this).val()});

    });
});


<select id="dropdown" name="dropdown">
    <option value="QU">QU</option>
    <option value="QF">QF</option>
    <option value="QC">QC</option>
</select>

答案 2 :(得分:0)

你必须这样做:

这是做什么的:

  1. 关于更改下拉列表
  2. 使用ajax,因此我们必须使用prevDef()
  3. 来阻止表单提交的默认行为
  4. 然后您的ajax调用submits the valueprocess it to process.php以及response on process.php gets loaded

    中的输出#output div
    $(document).ready(function() {
      $('#dropdown').change( function() {
           $.ajax({ // create an AJAX call...
               data: $(this).serialize(), // get the form data
               type: $(this).attr('method'), // GET or POST
               url: $(this).attr('action'), // the file to call
               success: function(response) { // on success..
                   $('#output').html(response); // update the DIV
               }
           });
        });
    });
    
相关问题