使用jquery将yii2 ajax请求中的两个参数传递给控制器

我有一个链接,当它按下它从控制器通过渲染ajax请求一个页面,以前我曾经只传递id但现在我想传递一个额外的参数到控制器,我怎么做到这一点,这就是我有的试着

这是仅将单个参数传递给控制器​​的链接

Html::a('click me', ['#'], ['value' => Url::to('checktruck?id='.$model->id), //this is where the param is passed 'id' => 'perform']); 

这是期望2个参数的控制器代码:

 public function actionChecktruck($id,$category) //it expects 2 parameters from above link { $truckdetails = Truck::find()->where(['id' =>$id])->one(); if (Yii::$app->request->post()) { $checklistperform = new TodoTruckChecklist(); $truck = Truck::find()->where(['id'=>$id])->one(); $checklistperform->truck_id=$id; $checklistperform->registered_by=Yii::$app->user->identity->id; $checklistperform->save(); $truck->update(); var_dump($checklistperform->getErrors()); //var_dump($truck->getErrors()); } else { $truckcategory = Checklist::find()->where(['truck_category'=>$truckdetails->truck_category])->andWhere(['checklist_category'=>$category])->all(); return $this->renderAjax('truckyard/_checklistform', [ 'truckcategory' => $truckcategory,'truckvalue'=>$id, ]); } } 

这是我的另一个按钮的jquery代码,它取决于post请求期间的上述控制器

 $("#postbutn").click(function(e) { $.post("checktruck?id="+truckid, //here i would like to pass 2 params {checked:checked,unchecked:unchecked,truckid:truckid} ) } 

这是没有post时的jquery代码

如何在链接中传递额外的参数,甚至是控制器的$ .post请求

首先,当您使用JQuery ajax提交表单时,无需为链接设置值

 Html::a('click me', ['#'],['id' => 'perform']); 

使用此ID您可以按如下方式提交请求

 $this->registerJs("$('#perform').click(function(event){ event.preventDefault(); // to avoid default click event of anchor tag $.ajax({ url: '".yii\helpers\Url::to(["your url here","id"=>$id,"param2"=>param2])."', success: function (data) { // you response here }, }); });"); 

没有必要提到方法属性为’POST’,你想通过GET方法发送

最后在您的控制器中,您需要接受如下参数

 public function actionChecktruck() //it expects 2 parameters from above link { $id = Yii::$app->request->queryParams['id']; $param2 = Yii::$app->request->queryParams['param2']; $truckdetails = Truck::find()->where(['id' =>$id])->one(); if (Yii::$app->request->post()) { $checklistperform = new TodoTruckChecklist(); $truck = Truck::find()->where(['id'=>$id])->one(); $checklistperform->truck_id=$id; $checklistperform->registered_by=Yii::$app->user->identity->id; $checklistperform->save(); $truck->update(); var_dump($checklistperform->getErrors()); //var_dump($truck->getErrors()); } else { $truckcategory = Checklist::find()->where(['truck_category'=>$truckdetails->truck_category])->andWhere(['checklist_category'=>$category])->all(); return $this->renderAjax('truckyard/_checklistform', [ 'truckcategory' => $truckcategory,'truckvalue'=>$id, ]); } } 

在View文件中尝试这个

 $this->registerJs("$('#postbutn').click(function(){ $.ajax({ url: '".yii\helpers\Url::to(["ur URL"])."', method: 'POST', data: {id:id, truckid:truckid }, success: function (data) { }, }); });");