问题
I have an AJAX call in my view. The code of it looks like this:
<?php
$this->registerJs("
$(document).on('click','.btn-block',function(){
var id = $(this).parents('.user-tr').attr('id');
$.ajax({
url: '" . Yii::$app->request->baseUrl . "admin/block-users',
type: 'POST',
data: {id : id,_csrf : " . Yii::$app->request->getCsrfToken() . "},
success: function (data) {
console.log(data);
},
});
})");
?>
I need to send a request to my actionBlockUsers
function of AdminController
, which looks like this:
public function actionBlockUsers()
{
if (Yii::$app->request->isAjax) {
print("success");
}
}
The problem is that I can't send a request. The inspect XHR doesn't show anything either. How can I fix this problem?
回答1:
You need to wrap the Yii::$app->request->getCsrfToken()
into quotes as it would normally contain ==
in the string which will break the script if not inside qutotes, a better way when working with javascript is to use the yii.js
to get the csrf token and the param name using yii.getCsrfParam()
and yii.getCsrfToken()
, rather than hard coding _csrf
.
Also you should try using hereDOC syntax for better readability.
So replace your code with the following in your view
$baseUrl=\yii\helpers\Url::base(true);
$js=<<<JS
$(document).on('click','.btn-block',function(e){
var id = $(this).parents('.user-tr').attr('id');
let data={id : id};
data[yii.getCsrfParam()]=yii.getCsrfToken();
$.ajax({
url: '{$baseUrl}/admin/block-users',
type: 'POST',
data: data,
success: function (data) {
console.log(data);
},
});
})
JS;
$this->registerJs($js, View::POS_READY);
来源:https://stackoverflow.com/questions/57506614/ajax-call-unable-to-send-a-request-yii2