我用yii2(2.0.13)。当我用ajax发送数据时,返回响应包含错误。
我的代码:
namespace frontend\controllers;
use Yii;
use yii\rest\ActiveController;
class CityController extends ActiveController
{
public $modelClass = 'frontend\models\City';
public function actions()
{
$actions = parent::actions();
unset($actions['create']);
return $actions;
}
public function behaviors()
{
$behaviors = parent::behaviors();
// remove authentication filter
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
return $behaviors;
}
public function actionCreate()
{
echo 'Hi i\'m create!!';
}
}
和ajax请求:
$.ajax({
url: "http://blog.dev/city", // our php file
type: 'POST',
contentType: false,
cache: false,
processData: false,
data: {x: 'data_text'},
success: function(data){
console.log(data);
},
error: function (request) {
console.log(request);
}
});
当在actionCreate中我添加exit()时问题得到解决。 问题出在哪里以及我应该如何更改actionCreate? 请帮帮我。
客户端发送ajax请求,因此Yii2也应该像ajax请求一样处理请求。你需要改变这样的代码:
<?php
...
public function actionCreate()
{
if (Yii::$app->request->isAjax) {
// DO SOMETHING
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'message' => 'Hi i\'m create!!'
];
}
}
客户端你可以有这样的东西:
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/ads' ?>',
type: 'post',
data: {
x: 'data_text',
_csrf : '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function (data) {
console.log(data.message);
}
});
重要!如果你在enableCsrfValidation
中有TRUE
,你需要发送CSRF令牌