Form表单ajax提交【pjax提交】
1、ajax提交后,pjax 刷新指定dom,也可以不加pjax
PHP Code复制内容到剪贴板
- <!-- ID是必填的,指定无刷新的dom名称 -->
- <?php \yii\widgets\Pjax::begin(['id' => 'comment-container', 'linkSelector' => false]) ?>
- .. //正常输入控制器传过来的变量即可
- <!-- data-ajax 必填表示为ajax提交 / data-refresh-pjax-container表示刷新哪一个dom -->
- <?php $form = ActiveForm::begin(['action' => Url::to(['/comment/create']), 'options' => ['data-ajax' => 1, 'data-refresh-pjax-container' => 'comment-container']]); ?>
- .. //正常写FORM
- <?= Html::submitButton('提交', [
- 'class' => 'btn btn-primary',
- ]) ?>
- <?php ActiveForm::end(); ?>
- <?php \yii\widgets\Pjax::end() ?>
FORM还支持属性:
data-refresh : 提交完成后是否刷新当前页(默认为否)
data-confirm : 提交之前是否弹出询问框(默认为否)
data-callback: 提交后的回调,支持funtion方法,支持string
data-method:传输方式,post/get
data-params 带参数传递,如:
XML/HTML Code复制内容到剪贴板
- 'data-params' => [ 'time' => $model['time'] ],
- 'data-callback' => '$("#modal-login").modal("hide")'
- 'data-callback' => 'window.parent.location.replace("'.$callbackUrl.'");'
2、定制ajax提交:
PHP Code复制内容到剪贴板
- <?php $form = ActiveForm::begin([
- 'options' => [
- 'class' => 'layui-form form-horizontal',
- ],
- 'fieldConfig' => [
- 'template' => '{label}<div class="col-sm-10">{input}</div><div class="col-sm-12">{error}</div>',
- 'labelOptions' => ['class' => 'col-sm-2 control-label'],
- ],
- 'id' =>'contractForm',
- 'enableAjaxValidation' => true, //必须设置,表示该表单以ajax提交
- ]); ?>
- <!-- 重要lay-filter lay-submit -->
- <?= Html::submitButton($model->isNewRecord ? '新增' : '更新', ['class' => $model->isNewRecord ? 'btn btn-success btn-flat' : 'btn btn-primary btn-flat','lay-submit'=>'','lay-filter'=>'contractForm']) ?>
- <?php ActiveForm::end(); ?>
- <!-- JS注册到底部 -->
- <?php $this->beginBlock('js') ?>
- <script>
- layui.use(['form', 'laydate'], function(){
- var form = layui.form, laydate = layui.laydate;
- //同时绑定多个
- lay('.select-time-item').each(function(){
- laydate.render({
- elem: this
- ,trigger: 'click'
- });
- });
- //监听提交
- form.on('submit(contractForm)', function(data){
- var action = data.form.action,field = data.field;
- var loading = layer.load(2);
- //表单提交
- $.ajax({
- url: action,
- type: 'post',
- data: field,
- success: function (res) {
- layer.close(loading);
- if(res.errcode){
- layer.open({
- title: '错误'
- ,content: res.errmsg
- });
- }else{
- layer.msg(res.errmsg, {
- time: 1000 // 2秒关闭(如果不配置,默认是3秒)
- }, function(){
- history.go(-1);
- });
- }
- },
- error: function () {
- layer.close(loading);
- layer.open({
- title: '错误'
- ,content: '系统错误,请联系管理员'
- });
- return false;
- }
- });
- return false;
- });
- });
- </script>
- <?php $this->endBlock() ?>
上一篇 编辑器
下一篇 选择用户(多选 / 单选)插件