AJAX呼叫无法发送请求Yii2 [英] AJAX call unable to send a request Yii2
问题描述
我的视线中有一个AJAX呼叫.它的代码如下:
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);
},
});
})");
?>
我需要向我的 AdminController
的 actionBlockUsers
函数发送请求,如下所示:
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");
}
}
问题是我无法发送请求.检查XHR也不显示任何内容.我该如何解决这个问题?
The problem is that I can't send a request. The inspect XHR doesn't show anything either. How can I fix this problem?
推荐答案
您需要像通常那样将 Yii :: $ app-> request-> getCsrfToken()
包装在引号中如果字符串中包含 ==
,则该字符串会破坏脚本(如果不在qutotes内),使用javascript时,更好的方法是使用 yii.js
来获取csrf令牌和使用 yii.getCsrfParam()
和 yii.getCsrfToken()
使用参数名称,而不是对 _csrf
进行硬编码.
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
.
此外,您应该尝试使用此处DOC 语法,以提高可读性.
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);
这篇关于AJAX呼叫无法发送请求Yii2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!