dongyi8383 2013-09-23 20:17
浏览 92
已采纳

如何使用AJAX / jQuery / JavaScript提交表单? [关闭]

I have a PHP website, which has a lot of forms that goes to certain pages on submit. So they look like this:

<form method='post' action='form_target.php'>
    <input type='text' name='fieldname' />
    <button type='submit'/>
</form>

I guess the same thing can be done with $.post('form-target.php');, without actually leaving the page. But I'm trying to prevent writing JavaScript code for a lot of different forms.

So is there a simple way to detect forms on the page, and convert them to AJAX calls? Maybe by bind onsubmit() , or onclick(); events to a $.post(); call?

Any help to implement this will also be appreciated.

  • 写回答

4条回答 默认 最新

  • dongren1011 2013-09-23 20:24
    关注

    You can attach the .submit event to all forms to catch the submission, then use .preventDefault() on the event object to prevent actual page submission (stop it from changing page). Then serialize the form's data (make a name-value paired string), get the url from the action attribute of the form element and then call jquery's ajax function

    using $("form") with nothing else as part of the selector will attach this to all forms on the page

    HTML

    <form method='post' action='form_target.php'>
        <input type='text' name='fieldname' />
        <button type='submit'/>
    </form>
    

    JAVASCRIPT

    $("form").submit(function(e){
        e.preventDefault();
        var data = $(this).serialize();
        var url = $(this).attr("action");
        $.ajax({
           url:url,
           type:"POST",
           data:data,
           success:function(){
              //do something when post succedes 
           },
           error:function() {
              // do something when it fails
           }
        });
    });
    

    <kbd>JQuery .ajax</kbd>

    <kbd>JQuery .serialize</kbd>

    <kbd>JQuery .submit</kbd>

    To further extend this you could make it so each form executes a specific success method, this would help in the case that you need something specific to happen for a specific form submission.

    First give each form a data-* attribute that we can later use in the submit event to trigger a specific function for that form.

    <form method='post' action='form_target.php' 
                        data-onerror="nameSubmitError" 
                        data-onsuccess="nameSubmitSuccess">
    

    Then create the two functions that we named in the data-* attributes

    function nameSubmitError() {
      //Do some code that will handle the error
    }
    
    function nameSubmitSuccess() {
      //Do some code that will handle the success
    }
    

    And in the .submit event

    $("form").submit(function(e){
        e.preventDefault();
        var data = $(this).serialize();
        var url = $(this).attr("action");
        var errorCallback = $(this).data("onerror");
        var successCallback = $(this).data("onsuccess");
        $.ajax({
           url:url,
           type:"POST",
           success:function(){
              //Check that we have a defined function before trying to execute it
              if( typeof(window[successCallback]) == "function" ) {
                 //We do have a defined function so execute it
                 window[successCallback]();
              }
           },
           error:function() {
              //Check that we have a defined function before trying to execute it
              if( typeof(window[errorCallback]) == "function" ) {
                 //We do have a defined function so execute it
                 window[errorCallback]();
              }
           }
        });
    });
    

    Of course putting all the callback functions in the global space would pollute it so you could setup all the functions into a single object and use the objects name instead of window

    var formCallbacks = {
        nameSubmitError:function() {
          //Do some code that will handle the error
        },
        nameSubmitSuccess: function() {
          //Do some code that will handle the success
        }
    };
    

    And in the .submit event change window to formCallbacks

    //window[errorCallback]();
    //Becomes 
    formCallbacks[errorCallback]();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 VMware安装虚拟网络驱动程序不成功,如何解决?(操作系统-linux)
  • ¥15 MAC安装佳能LBP2900驱动的网盘提取码
  • ¥400 微信停车小程序谁懂的来
  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥15 QFILHelper怎么恢复全字库,提示进程已完成,只能恢复分区文件