第一种解决办法是关闭Csrf
1、局部关闭:public function init(){ $this->enableCsrfValidation = false; }
2、全局关闭:在配置文件中(main-local.php或web.php)设置为"enableCsrfValidation"=> false,//true开启csrf验证
第二种解决办法是在form表单中加入隐藏域;name="_csrf"为框架默认配置
<input name="_csrf" type="hidden" id="_csrf" value="<?= Yii::$app->request->csrfToken ?>">
第三种解决办法是在AJAX中加入_csrf字段,但是表单不能有<form></form>标签
$(function(){
$('.submit').click(function()
{
var id = $("input[name='id']").val();
var name = $("input[name='row[name]']").val();
var nickname = $("input[name='row[nickname]']").val()
var mobile = $("input[name='row[mobile]']").val()
var email = $("input[name='row[email]']").val()
//var csrfToken = $('input[name="_csrf"]').val()
var csrfToken = $('meta[name="csrf-token"]').attr("content");
//alert(csrfToken);return false;
$.ajax({
type: "POST",
url: "<?= \yii\helpers\Url::to(['test/ajaxedit']) ?>",///index.php?r=test/ajaxedit
//data: {username:$("#username").val(), content:$("#content").val()},
data: {id:id,name:name,nickname:nickname,mobile:mobile,email:email,_csrf:csrfToken},
dataType: "json",
success: function(data)
{
alert(data.msg);
window.location.href = "<?= \yii\helpers\Url::to(['/test/index']); ?>";
}
});
});
});
php中对应的函数:
/**
* ajax更新数据
*/
public function actionAjaxedit()
{
$request = \Yii::$app->request;
if ($request->isAjax)
{
$params = $request->bodyParams;
if(isset($params))
{
$test = Test::findOne($request->post('id'));
$test->name = $params['name'];
$test->nickname = $params['nickname'];
$test->mobile = $params['mobile'];
$test->email = $params['email'];
$test->update_time = time();
$result = $test->save();//$test->update()
VarDumper::dump($result);exit();
$test = $result ? ['code'=>200,'msg'=>'成功!!!'] : ['code'=>400,'msg'=>'失败!!!'];
}
else
{
$test = ['code'=>400,'msg'=>'数据不能为空!!!'];
}
return \yii\helpers\Json::encode($test);
}
return \yii\helpers\Json::encode(['code'=>400,'msg'=>'请求错误!!!']);
}