yii2 ajax的post提交問題
第一種解決辦法是關閉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'=>'請求錯誤!!!']);
}