在我的Yii2中,我正在尝试编写自己的ajax请求以执行删除操作。
我的操作列按钮代码 **
'delete' => function ($url, $model) {
return '<span class="glyphicon glyphicon-trash delete-prod" id="'.$model->product_id.'" style="cursor:pointer;"></span>';**
},
我的Ajax请求:
<?php
if($model!= null){
foreach($model as $mod);
}
$this->registerJs('
jQuery("body").on("click", ".delete-prod", function() {
var id = $(this).attr("id").split("-")[1];
alert(id);
$.ajax({
type: "POST",
cache: false,
data:{"refID": id},
url: "'.Yii::$app->getUrlManager()->createUrl("product/delete?id=".$mod->product_id).'",
dataType: "json",
success: function(data){
if(data.status){
alert("hello");
}else{
alert(data.message);
}
}
});
});
');
?>
我在控制器中的删除操作
public function actionDelete($id)
{
\app\models\Productlines::find()->where(['product_id' => $id])->one()->delete();
return $this->redirect(['index']);
}
出于某种原因,我只是在点击按钮时收到警报。我的删除操作不起作用。我收到 500内部服务器错误。任何人都可以帮我解决这个问题吗?
万分感谢...
答案 0 :(得分:2)
试试这个
您的删除按钮代码
'delete' => function ($url, $model) {
return '<span class="glyphicon glyphicon-trash delete-prod"
data-id="'.json_encode(["prod_id" => $model->product_id,"area_id" => $model->area_id]).'" style="cursor:pointer;"></span>';
},
您的ajax请求代码
$url=Yii::$app->getUrlManager()->createUrl("product/delete");
$this->registerJs('
jQuery("body").on("click", ".delete-prod", function() {
try{
var model_obj = JSON.parse($(this).attr("data-id"));
alert(model_obj.prod_id); //check whether you are getting the correct prod_id value
var prod_id = model_obj.prod_id;
var area_id = model_obj.area_id;
$.ajax({
type: "POST",
cache: false,
data:{"prod_id":prod_id,"area_id":area_id},
url: "'.$url.'",
dataType: "json",
success: function(data){
alert(data.status);
}
});
}
catch(e)
{
alert(e); //check tosee any errors
}
});
');
您的控制器代码
public function actionDelete()
{
Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
$p = Yii::$app->request->post();
$prod_id=$p["prod_id"];
$area_id=$p["area_id"];
if(\app\models\Productlines::find()->where(['product_id' => $id])->one()->delete())
{
return [
"status" => "success"
];
}
else
{
return [
"status" => "failure"
];
}
}