YII2框架中使用yii.js实现的post请求
yii2提供了很多帮助类,比如Html、Url、Json等,可以很方便的实现一些功能,下面简单说下这个Html。用yii2写view时时经常会用到它,今天在改写一个页面时又用到了它。它比较好用的地方就在于,它不仅仅是生成一个简单的html标签,结合yii2自己的静态资源文件yii.js可以很方便的实现一个post请求。 yii2将这些功能都做好了封装,只要在合适的地方调用它的方法就可以了,可以说yii2是个可以开箱即用的框架,你可以用它很快的实现一个需要的功能:比如在页面中放置一个删除按钮,点击按钮发送post请求,弹出确认对话框。如果没有yiihelpersHtml类和yii.js,那么你需要写大量的js/jquery来实现这个功能。如果用yii2的话,下面的代码就可以实现: $id,],[
'data' => [
'confirm' => '你确定要删除吗?','method' => 'post',]
)
?>
// html代码
它会在页面中生成下面一段html代码: 点击这个按钮会弹出对话框,确认删除后会发送post请求。那么这个post请求是如何发送的呢?到现在为止可是一段js代码都没写呢。 yii2框架隐藏了技术实现的细节,post请求的实现在yii.js中。在yii.js中,定义了window.yii对象,并初始化了window.yii对象的initModule方法: },// 其他省略
}; window.jQuery(function () { 其中上面的initDataMethods()会调用pub.handleAction方法: if (method === undefined && message === undefined && form === undefined) {
return true;
}
if (message !== undefined) {
$.proxy(pub.confirm,this)(message,function () {
pub.handleAction($this,event);
});
} else {
pub.handleAction($this,event);
}
event.stopImmediatePropagation();
return false;
};
// handle data-confirm and data-method for clickable and changeable elements
$(document).on('click.yii',pub.clickableSelector,handler)
.on('change.yii',pub.changeableSelector,handler);
} 可以看到这个方法会获取上面生成的a标签的data属性值,然后交给handlerAction来处理。handlerAction通过动态生成一个form来处理各种请求,最后通过触发submit事件来提交。 $form = $('',{method: method,action: action});
var target = $e.attr('target'); if (target) { $form.attr('target',target); } if (!/(get|post)/i.test(method)) { $form.append($('',{name: '_method',value: method,type: 'hidden'})); method = 'post'; $form.attr('method',method); } if (/post/i.test(method)) { var csrfParam = pub.getCsrfParam(); if (csrfParam) { $form.append($('',{name: csrfParam,value: pub.getCsrfToken(),type: 'hidden'})); } } $form.hide().appendTo('body'); // 其他省略 PS:做项目用框架很方便,但是框架用的久了,就容易把基本的技术给忘掉了。还是要打好基础呀,这样不管用什么框架都不至于用得云里雾里的。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |