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 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体