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 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记