我創建使用AJAX(鏈接和表單)
<?php
namespace app\component;
use smallbearsoft\ajax\AjaxAsset;
use Yii;
use yii\widgets\Pjax;
class myPjax extends Pjax{
public $ajaxLink=false;
public $ajaxForm=false;
public $multiAjaxLink=false;
public $params=[];
function init()
{
if($this->ajaxLink==true)
{
$this->Link($this->params);
}
if($this->ajaxForm==true)
{
$this->ajaxForm($this->params);
}
if($this->multiAjaxLink==true)
{
$this->multiLink($this->params);
}
parent::init();
}
public function Link()
{
$id=$this->params['id'];
$url=$this->params['url'];
$dviId=$this->params['divId'];
$url=Yii::$app->urlManager->createAbsoluteUrl($url);
$js2="$('#".$id."').on('click', function() { $.ajax({url: '".$url."',type: 'POST',success : function(res){ $('#".$dviId."').html(res);}});});";
$view = $this->getView();
AjaxAsset::register($view);
if ($js2 !== '') {
$view->registerJs($js2);
}
return ;
}
public function multiLink()
{
foreach($this->params as $value=>$key):
$id=$key['id'];
$url=$key['url'];
$dviId=$key['divId'];
$url=Yii::$app->urlManager->createAbsoluteUrl($url);
$js2="$('#".$id."').on('click', function() { $.ajax({url: '".$url."',type: 'POST',success : function(res){ $('#".$dviId."').html(res);}});});";
$view = $this->getView();
AjaxAsset::register($view);
$view->registerJs($js2);
endforeach;
return ;
}
public function ajaxForm()
{
$form_id=$this->params['id'];
$divId=$this->params['divId'];
$url=Yii::$app->urlManager->createAbsoluteUrl($this->params['url']);
$js2=" $('#$form_id').submit(function(e){ $.ajax({url : '$url',type: 'POST',data : $(this).serializeArray(),success:function(res){ $('#$divId').html(res);}});e.preventDefault();e.unbind();});";
$view = $this->getView();
AjaxAsset::register($view);
$view->registerJs($js2);
return ;
}
static function ajaxForm2($url,$idform=null,$dviId='show',$type='POST')
{
$pop="$.ajax({type:'".$type."',url :' ".$url." ',data: $('#".$idform."').serialize(),success:function(res){ $('#".$dviId."').html(res);}})";
echo $pop;
}
public function registerClientScript()
{
}
}
,並使用新的extention:
<?php myPjax::begin(['multiAjaxLink'=>true,
'params'=>[
['url'=>['controller/action'],'id'=>'id-link','divId'=>'where-show'],
['url'=>['controller/action'],'id'=>'id-link','divId'=>'where-show'],
['url'=>['controller/action'],'id'=>'id-link','divId'=>'where-show'],
]
]) ?>