代码之家  ›  专栏  ›  技术社区  ›  Alec

使用jQuery处理表单数据

  •  1
  • Alec  · 技术社区  · 17 年前

    function post(div,url,formId) {
      new Ajax.Updater(div, url, {
        asynchronous:true, 
        parameters:Form.serialize(formId)
      });
    }

    附带的HTML示例:

    <form method="post" action="" id="foo" 
      onsubmit="post('result','getdata.php','foo');return false;">
      <input type="text" name="data" />
    </form>
    <div id="result">&lt/div>

    提前感谢你的帮助。

    3 回复  |  直到 14 年前
        1
  •  8
  •   Paolo Bergantino    17 年前

    使用此HTML:

    <form method="post" action="getdata.php" id="foo">
      <input type="text" name="data" />
    </form>
    <div id="result"></div>
    

    $(function() { // wait for the DOM to be ready
        $('#foo').submit(function() { // bind function to submit event of form
            $.ajax({
                type: $(this).attr('method'), // get type of request from 'method'
                url: $(this).attr('action'), // get url of request from 'action'
                data: $(this).serialize(), // serialize the form's data
                success: function(responseText) {
                    // if everything goes well, update the div with the response
                    $('#result').html(responseText);
                }
            });
            return false; // important: prevent the form from submitting
        });
    });
    

    我为什么要把它扔掉 onsubmit 代码是因为这样的内联JavaScript被认为是不好的做法。您应该努力使表单不含JavaScript,然后将所有JavaScript绑定到表单之外。这被称为不引人注目的JavaScript,这是一件好事。

    编辑

    由于您在许多页面中都有该代码,因此这是一个函数,它将使用您当前在post函数中拥有的相同签名来执行您想要的操作。我建议你花几个小时来更新你的所有表格,但无论如何,这里是:

    function post(div,url,formId) {
        $.post(url, $('#' + formId).serialize(), function(d) {
            $('#' + div).html(d);
        });
    }
    

    livequery 插件可以帮你。或者,它可以简单地将绑定代码封装在函数中,并在添加表单时调用它。

        2
  •  0
  •   John Sheehan    17 年前

    $(document).ready(function() {
        $("#foo").submit(function() {
            $.post($(this).attr("action"), $(this).serialize());
            return false; // prevent actual browser submit
        });
    });
    

    jQuery serialize method docs

        3
  •  -3
  •   Caner    16 年前

    由于安全问题,无法使用jquery发送“多部分/表单数据”表单。你必须用flash或iframe来完成它。。。