如何在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.