I want to do a web project using Yii2, and I want to return a JSON to AJAX. I have used json_encode()
and Yii::$app->response->format = Response::FORMAT_JSON;
, but it still doesn't work.
Here is my action:
public function actionAbout(){
Yii::$app->response->format = Response::FORMAT_JSON;
return json_encode(["test"=> 1]);
}
Here is my AJAX:
$.ajax({
type: "POST",
// dataType: 'json',
data: {
'user': 'A'
},
url: "?site/about",
contentType: "application/json",
success: function(data) {
console.log(typeof(data));
console.log(data)
},
error: function (data) {
console.log(data);
},
});
But it returns this:
<!DOCTYPE html>....
still a html. How to solve it?