2

我有以下调用另一个文件并根据下拉值吐出输出。它工作正常,但我似乎无法在没有提交按钮的情况下正常工作。这有效,除了它将自己重定向到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>
4

3 回答 3

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
           }
       });
    });
});
于 2012-12-19T17:42:01.270 回答
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>
于 2012-12-19T17:47:07.837 回答
0

你必须这样做:

这是在做什么:

  1. 更改下拉菜单
  2. 使用ajax,所以我们必须防止表单提交的默认行为prevDef()
  3. 然后你的ajax 调用 whichsubmits 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
               }
           });
        });
    });
    
于 2012-12-19T17:44:06.287 回答