【问题标题】:Silverstripe: CMS Pages as JSON?Silverstripe:作为 JSON 格式的 CMS 页面?
【发布时间】:2013-07-01 20:41:05
【问题描述】:

我正在从事 Silverstripe 项目,我希望有一种简单的方法将 CMS 生成的页面(或页面的子类型)的内容呈现为 JSON。

理想情况下,我想在路由末尾附加“/json”,或者通过 post (json=true) 发送参数并获取 JSON 格式的响应。

我尝试向我的 CustomPage_Controller 类添加一个操作,如下所示:

public static $allowed_actions = array('json');
public function json(SS_HTTPRequest $request) {
    // ...
}

但我不知道如何做到这一点:

  • 我应该使用什么 URL/路由?
  • 如何获取页面内容?

【问题讨论】:

  • 不用说这是我第一次使用 Silverstripe,所以这可能是一个非常基本的问题。但是,在谷歌搜索了一段时间后,我无法得到我正在寻找的答案。

标签: php json api silverstripe


【解决方案1】:

你在正确的轨道上。您只需在 json 操作中执行类似的操作:

public function json(SS_HTTPRequest $request) {

    $f = new JSONDataFormatter();
    $this->response->addHeader('Content-Type', 'application/json');
    return $f->convertDataObject($this->dataRecord);

}

或者对于特定字段,您可以这样做:

public function json(SS_HTTPRequest $request) {

    // Encode specific fields
    $data = array();
    $data['ID'] = $this->dataRecord->ID;
    $data['Title'] = $this->dataRecord->Title;
    $data['Content'] = $this->dataRecord->Content;

    $this->response->addHeader('Content-Type', 'application/json');
    return json_encode($data);

}

如果您将上述内容放在 Page.php 文件中的控制器内,并且所有其他页面都扩展 Page_Controller,那么您应该能够转到 http://mydomain/xxxx/json 并获取任何页面的 JSON 输出。

【讨论】:

  • 您可能希望在输出中添加适当的内容类型。像这样:$this->response->addHeader('Content-Type', 'application/json');
  • 这就像一个魅力。我也遇到了一些作为 JSON 响应一部分的 HTML 的问题,但是按照@bummzack 的建议添加了适当的内容类型标头,解决了这个问题。谢谢!
  • 这在 2021 年仍然是一个好答案吗?似乎 JSONDataFormatter 不在 4.x 中api.silverstripe.org/4/search.html?search=JSONDataFormatter
【解决方案2】:

Shane 的回答很有帮助,但是我需要输出路线中的所有页面,而不仅仅是当前记录。

这是我设法做到这一点的方法:

<?php

class Page_Controller extends ContentController {

    private static $allowed_actions = [
        'index',
    ];

    public function init() {
        parent::init();
        // You can include any CSS or JS required by your project here.
        // See: http://doc.silverstripe.org/framework/en/reference/requirements
    }

    public function index(SS_HTTPRequest $request) {
        $results = [];
        $f = new JSONDataFormatter();
        foreach (Article::get() as $pageObj) {
            $results[] = $f->convertDataObjectToJSONObject($pageObj);
        }

        $this->response->addHeader('Content-Type', 'application/json');
        return json_encode($results);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 2016-02-14
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    相关资源
    最近更新 更多