我有一个链接,按下时它通过渲染ajax从 Controller 请求页面,以前我只传递id,但现在我想向 Controller 传递一个额外的参数,我如何实现这一点, 这是我尝试过的
这是仅将单个参数传递给 Controller 的链接
Html::a('click me', ['#'],
['value' => Url::to('checktruck?id='.$model->id), //this is where the param is passed
'id' => 'perform']);
这是需要 2 个参数的 Controller 代码:
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 代码,该按钮在发布请求期间依赖于上述 Controller
$("#postbutn").click(function(e) {
$.post("checktruck?id="+truckid, //here i would like to pass 2 params
{checked:checked,unchecked:unchecked,truckid:truckid}
)
}
这是没有post时的jquery代码
我如何在链接中传递额外的参数,甚至是 Controller 的 $.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 方法发送
最后在你的 Controller 中,你需要接受如下参数
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,
]);
}
}
关于javascript - 使用 jquery 将 yii2 ajax 请求中的两个参数传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39834538/