CakePHP的 - 如何从控制器动作返回字符串(如JSON)到Ajax请求 [英] CakePHP - How to return string (like JSON) from controller action to Ajax request
问题描述
所以,我有我的JavaScript调用Ajax来 / my_controller / ajax_action
但随后在控制器中,我不知道该怎么做才能输出回馈给JavaScript
So I have my JavaScript making an Ajax call to /my_controller/ajax_action
but then in the controller I don't know what to do to output something back to the JavaScript.
我收到错误,因为没有视图 :: myController的ajaxAction()
但显然没有认为它,所以我该怎么办?
I am getting errors because there is no view for MyController::ajaxAction()
but obviously there is no view for it, so what do I do?
推荐答案
做到这一点,必须要在一个阵列输出的变量假设 $的数据
,然后通过使用数组视图的 $这个 - >集(数据,$数据);
的方法,然后创建一个视图 /一般/ SerializeJson.ctp
。在这个视图文件,把< PHP回声json_en code($的数据); ?>
之后,你可以使用 $这个 - >渲染('/一般/ SerializeJson');
,它应该输出的JSON。
do this, have your variables you want to output in an array let's say $data
, then pass that array to the view using the $this->set('data', $data);
method, then create a view /General/SerializeJson.ctp
. In that view file, put <?PHP echo json_encode($data); ?>
after that you can use $this->render('/General/SerializeJson');
and it should output the json.
常规code ...
General code...
/Controllers/MyController.php
public class MyController extends AppController
{
public function ajaxAction()
{
$data = Array(
"name" => "Saad Imran",
"age" => 19
);
$this->set('data', $data);
$this->render('/General/SerializeJson/');
}
}
/Views/General/SerializeJson.ctp
<?PHP echo json_encode($data); ?>
这篇关于CakePHP的 - 如何从控制器动作返回字符串(如JSON)到Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!