CakePHP - 如何从控制器操作返回字符串(如 JSON)到 Ajax 请求 [英] CakePHP - How to return string (like JSON) from controller action to Ajax request

查看:23
本文介绍了CakePHP - 如何从控制器操作返回字符串(如 JSON)到 Ajax 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的 JavaScript 对 /my_controller/ajax_action 进行了 Ajax 调用,但随后在控制器中我不知道如何将某些内容输出回 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?

推荐答案

这样做,让你想在数组中输出的变量让我们说 $data,然后将该数组传递给视图使用$this->set('data', $data); 方法,然后创建一个视图 /General/SerializeJson.ctp.在该视图文件中,输入 <?PHP echo json_encode($data);?> 之后你可以使用 $this->render('/General/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.

通用代码...

/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆