Drupal 创建一个输出 JSON 的页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3636463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:33:52  来源:igfitidea点击:

Drupal create a page that outputs JSON

jsondrupal

提问by r2b2

I would like to ask can one create a page that outputs JSON data as a response to Jquery Ajax request?

我想问一下,可以创建一个输出 JSON 数据作为对 Jquery Ajax 请求的响应的页面吗?

In a non-drupal way, I would just create a php file, for example mypage.php and then I would use http://example.com/mypage.php?foo=baras the URL for my AJAX request. This page will then output JSON data using json_encode().

在非 Drupal 方式中,我将只创建一个 php 文件,例如 mypage.php,然后我将使用http://example.com/mypage.php?foo=bar作为我的 AJAX 请求的 URL。此页面将使用 json_encode() 输出 JSON 数据。

How can I do it the Drupal way?

我怎样才能以 Drupal 的方式做到这一点?

回答by commonpike

A working example of scott reynen's hint: in drupal 7, in a module called mymodule, write

scott reynen 提示的一个工作示例:在 drupal 7 中,在名为 mymodule 的模块中,写

function mymodule_menu() {
    $items['fancystuff/json'] = array(
        'access callback'   => true, // available to all
        'page callback'     => 'mymodule_fancystuff_object', // defined below
        'delivery callback' => 'drupal_json_output' 
    );
    return $items;
}



function mymodule_fancystuff_object() {
    return array('test'=>true,'dummy'=>array(0,1));
}

clear your caches, goto http://example.com/fancystuff/jsonand behold

清除缓存,转到http://example.com/fancystuff/json并查看

回答by Scott Reynen

The JSON server modulegives you JSON output of nodes.

JSON服务器模块为您提供了节点的JSON输出。

If you want more custom JSON, you can use hook_menu()to create a new menu callback (basically a URL path pointed to a function) and then use:

如果你想要更多的自定义 JSON,你可以使用hook_menu()创建一个新的菜单回调(基本上是一个指向函数的 URL 路径),然后使用:

within that callback to send the output as JSON rather than the default HTML.

在该回调中将输出作为 JSON 而不是默认 HTML 发送。