开发者

Drupal create a page that outputs JSON

开发者 https://www.devze.com 2023-01-14 22:35 出处:网络
I would like to ask can one create a page that outputs JSON data as a response to Jquery Ajax request?

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

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=bar as the URL for my AJAX request. This page will then output JSON da开发者_Python百科ta using json_encode().

How can I do it the Drupal way?


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

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/json and behold


The JSON server module gives you JSON output of nodes.

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:

  • drupal_json() - Drupal6
  • drupal_json_output() - Drupal7

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

0

精彩评论

暂无评论...
验证码 换一张
取 消