【问题标题】:Ajax with CakePHP and Javascript使用 CakePHP 和 Javascript 的 Ajax
【发布时间】:2018-05-20 10:59:31
【问题描述】:

我在使用 CakePHP 和 Javascript 方面还很新,我阅读了很多关于 cake 中请求处理的文章,但我仍然感到困惑,我正在尝试做的是将 ajax 请求从我的 Javascript 代码发送到 cakePHP 和获取一些 json 格式的数据,我尝试了很多方法来做到这一点,但我一直只得到页面的 html,而不是我想要获取的数据,我默认生成了应用程序控制器类,作为 Javascript 请求中的 url 我使用“http://localhost/pages/main”,这是我有输入控件的视图页面的 url,我想知道我应该在控制器类中的哪个位置放置负责处理请求的代码,以及如何实现发送 json 响应,提前谢谢

php代码AppController类

public function beforeRender(Event $event)
{
    // Note: These defaults are just to get started quickly with development
    // and should not be used in production. You should instead set "_serialize"
    // in each action as required.
    if (!array_key_exists('_serialize', $this->viewVars) &&
        in_array($this->response->type(), ['application/json', 'application/xml'])
    ) {
        $this->set('_serialize', true);

        if ($this->request->is('ajax')) {
            $data = ['data1', 'data2'];
            $this->set(compact('data'));
            $this->set('_serialize', ['data']);
        }
    }

    **javascript:**


    var xhr = new XMLHttpRequest();
    var url = 'localhost/pages/main.json';
    var data = {
        unit: 'someUnit',
        name: this.name
    };

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            console.log(xhr.response);
        }
    };
    xhr.open('POST', url);
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send(data);

【问题讨论】:

  • 你能给我们看看你的 PHP 和 JS 代码吗?

标签: javascript php jquery ajax cakephp


【解决方案1】:

如果你使用routing extension会更容易

Router::extensions(['json']);

然后在您的控制器中,您可以像这样传递serialize data

$data = $this->Model->find();
$this->set(compact('data');
$this->set('_serialize', ['data']);

在您的 ajax 请求中,只需将 .json 扩展名添加到 url

【讨论】:

  • 我添加了 routes.php 扩展,我添加了 php 和 js 代码 - 它与帖子中的相同,但仍然无法正常工作:/
【解决方案2】:

您可以从这里开始:CakePHP official documentation for REST

例子:

// src/Controller/RecipesController.php
class RecipesController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
    }

    public function index()
    {
        $recipes = $this->Recipes->find('all');
        $this->set([
            'recipes' => $recipes,
            '_serialize' => ['recipes']
        ]);
    }
}

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 2014-08-09
  • 2016-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多