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 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块