我在 Yii2 中使用 pjax,我在使用 pjax 时遇到了问题。所有脚本仅在第一次和发送 pjax 请求并更新表内容后正常工作,脚本和 pjax 不起作用。如果我删除该行$.pjax.reload({container:'#products-table'});
则所有脚本都在工作。而且我也发现了这个解决方案(Yii2 Pjax 和 ActiveForm beforeSubmit 在重新加载后不起作用?):"$(document).on('ready pjax:success', function(){ // to do });
"并且它工作正常,但在添加更多 jquery 代码后它再次停止工作。如果有人有同样的问题,请与解决方案分享。谢谢!
$(document).on('ready pjax:success', function(){
$(".product-edit-submit").on('click', function(){
$.ajax({
type : "POST",
url : editUrl,
data: {
id: this.id,
productName: productName,
productCost: productCost,
_csrf: csfr
},
success : function(response) {
$.pjax.reload({container:'#products-table'});
},
error : function(response){
console.log(response);
}
});
return false;
});
});
视图:
<?php Pjax::begin(['id' => 'products-table']); ?>
<table class="table table-hover table-striped">
.......
</table>
<?php Pjax::end(); ?>
只需更改此行$(".product-edit-submit").on('click', function(){
自:
$(document).on('click', '.product-edit-submit', function () {
然后它会工作
如果您的代码在添加额外的库后停止,请尝试在视图中注册它以确保它将在包含的所有库之后执行:
<?php
$js = <<< 'JAVASCRIPT'
$(document).on('ready pjax:success', function(){
$(".product-edit-submit").on('click', function(){
$.ajax({
type : "POST",
url : editUrl,
data: {
id: this.id,
productName: productName,
productCost: productCost,
_csrf: csfr
},
success : function(response) {
$.pjax.reload({container:'#products-table'});
},
error : function(response){
console.log(response);
}
});
return false;
});
});
JAVASCRIPT;
$this->registerJs($js,'yii'web'View::POS_READY);
我找到了第二次脚本没有触发的原因。我把剧本放在$(document).on('ready pjax:success', function(){ //code });
外面.把它放在pjax:success
里面后,所有的脚本都重新工作了。谢谢!
例如,假设以下文档:
<div id="a">
<?php Pjax::begin() ?>
<div id="b">
...
</div>
<?php Pjax::end() ?>
</div>
现在,当你想要处理"#b"的事件时,你可能想这样写:
<script>
$("#b").on("someEvent", function(){…});
</script>
但它仅适用于第一个事件。当 pjax 更新"#b"时,事件处理程序将丢失。它不适用于第 2 次事件及之后。
脚本应为:
<script>
$("#a").on("someEvent", "#b", function(){…});
</script>
这会将事件处理程序附加到"#a",但处理程序处理"#b"的事件。由于"#a"位于 pjax 区域之外,因此当 pjax 更新"#b"时,事件处理程序不会丢失。