如何在yii2中发送ajax表单 [英] How to send an ajax form in yii2

查看:27
本文介绍了如何在yii2中发送ajax表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 yii2 应用程序中的 html 表单发送数据.我需要使用ajax从这个表单发送数据并从服务器获取响应以输出它.在 yii 1.0 中,我使用了非常有用的助手 ajaxSubmitButton,但在 yii2 中我找不到如何使用 ajax 从表单发送数据.你能告诉我怎么做吗?有没有关于它的文章?

I need to send data from html form in my yii2 app. I need to use ajax to send data from this form and get the response from server to output it. In yii 1.0 i was using very useful helper ajaxSubmitButton and i can't find how to send data from form with ajax in yii2. Could you tell me how to do it? Is there any article about it?

谢谢.

推荐答案

Yii ActiveForm 在其生命周期的许多阶段都支持 JavaScript 事件.您可以使用 beforeSubmit 事件来实现您想要的.在 JavaScript 中:

Yii ActiveForm supports JavaScript events in many stages of its life cycle. You can use beforeSubmit event for achieving what you are looking for. In JavaScript:

$(document).ready(
    $('#myform').on('beforeSubmit', function(event, jqXHR, settings) {
        var form = $(this);
        if(form.find('.has-error').length) {
            return false;
        }

        $.ajax({
            url: form.attr('action'),
            type: 'post',
            data: form.serialize(),
            success: function(data) {
                // do something ...
            }
        });

        return false;
    }),
);

请注意,您可以通过从事件回调中返回 false 来停止表单的正常提交.

Note that you can stop the normal submission of the form by returning false from the event callback.

这篇关于如何在yii2中发送ajax表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆