简体   繁体   English

提交表单后可以发起ajax调用吗?

[英]Is it ok to initiate an ajax call after form submission ?

An ajax post request will be issued after form submission. 提交表单后,将发出ajax发布请求。

I want to call the ajax post after submission of the form. 提交表单后,我想打电话给ajax发布。

But ajax call is issued before form submission, should I need to delay the ajax call? 但是ajax调用是在表单提交之前发出的,我是否需要延迟ajax调用? how to do that after form submission? 表单提交后该怎么办?

by submitting form I'm calling an add function to save data 通过提交表单,我正在调用添加函数来保存数据

$("#section-form").submit(function (e) {


    save_class_info();

});

function save_class_info() {

   var  action = 'saveclassinfo';


    var campus_info = {
        'campus_name': campus_name,
        'shift_name': shift_name,
        'medium_name': medium_name,
        'class_name': class_id,
        'teacher_id': teacher_id,
        'edit': 'false'
    };

    $.ajax({
        url: "/" + root + "/" + controller + "/" + action,
        type: "post",
        data: campus_info,
        success: function (response) {

            console.log('done');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus, errorThrown);
        }


    });
}

You need to disable default form submission behaviors by using preventDefault : 您需要使用preventDefault禁用默认的表单提交行为:

$("#section-form").submit(function (e) {
    e.preventDefault();
    save_class_info();
});

Try to prevent form submit. 尝试防止表单提交。

$("#section-form").submit(function (e) {
    e.preventDefault();
    e.stopPropagation();
    save_class_info();
});

That was my mistake.During form submission I can't issue an ajax call because that page will be refreshed after submitting the form. 那是我的错误。在提交表单期间,我无法发出ajax调用,因为提交表单后,该页面将被刷新。 So I've done the submission of the form through another ajax call and after that call, I've issued another ajax post cause I need the data from success of 1st ajax call. 因此,我通过另一个ajax调用完成了表单的提交,在该调用之后,我发布了另一个ajax发布,因为我需要从第一次ajax调用成功中获取数据。

Thanks all for letting me know the problem of my approach. 谢谢大家让我知道我的方法的问题。

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

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