欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

drupal 7 drupal7 d7 output json example ajax 例子 有大用 有大大用

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

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

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



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

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

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


来自  https://stackoverflow.com/questions/3636463/drupal-create-a-page-that-outputs-json



Getting Started with JSON in Drupal 7

How can you transfer data between websites? There are many options and modules for Drupal out there. You can use the ServicesRESTful Web Services or Views Datasource module. However, using those modules can sometimes be a bit overkill. If all you want to do is expose some data via JSON so that it's accessible for other websites, then it’s easier to create a custom menu item and just return the exposed data as JSON from a menu callback.

In this article, we'll look at encoding and decoding JSON within Drupal as well as creating a JSON endpoint for content.

Drupal offers two functions for encoding and decoding JSON. To encode an array into JSON use drupal_json_encode() and to decode a JSON object into an array use the – can you guess it? – drupal_json_decode() function.

Download source files from GitHub.

Encoding JSON

First, let’s look at encoding an array into JSON. Take this array for example:

$array = array('Boat', 'Car', 'Ship', 'Building');

If we were to encode the above array into JSON, you will get ["Boat","Car","Ship","Building"] returned. Here is a code example:

image.png

$array = array('Boat', 'Car', 'Ship', 'Building');
$output = drupal_json_encode($array);
// $output will be ["Boat","Car","Ship","Building"]

Decoding JSON

Now let's look at decoding a JSON object. If you were to running the following code:

image.png

$json = '["Boat","Car","Ship","Building"]';  
return drupal_json_decode($json);

The drupal_json_decode() function will return an array.

So far we have looked at the drupal_json_encode() and drupal_json_decode() function and have seen how simple they are to use.

Pulling In JSON Objects

The next example I want to demonstrate is how to pull in a Twitter account using Twitter's GET users/show REST API.

First, we’ll need to get the JSON object and for this we’ll use the drupal_http_request() function:

image.png

$request = drupal_http_request('https://api.twitter.com/1/users/show.json?screen_name=TwitterAPI&include_entities=true');

Within the $request variable, there will be a data property $request->data. This stores the JSON object.

The only thing left to do is decode the data property to get access to all the information.

image.png

$request = drupal_http_request('https://api.twitter.com/1/users/show.json?screen_name=TwitterAPI&include_entities=true');
return drupal_json_decode($request->data);

Example of the decoded array:

JSON Endpoints

The last item I want to demonstrate is how to create a JSON endpoint for content on a Drupal site. For example, if you navigate to example.com/node/1/json the website will output a JSON version of the content. This will show you how to output a full JSON page using the drupal_json_output() function.

NOTE: If you want to create JSON or XML endpoints on a production site look at using the Services module.

  1. First we must implement a menu item using the hook_menu. The menu item path needs to be "node/%node/json". For more details on how to use hook_menu check out the API documentation.

  2. image.png

/**
 * Implements hook_menu().
 */
function ww_json_example_menu() { 
  $items['node/%node/json'] = array(
    'page callback' => 'ww_json_example_endpoint',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
  );
  return $items;
}

2. Create a "page callback" function for the menu item. Also, make sure that you add a $node variable to the function signature. For this example, the page callback is "ww_json_example_endpoint". Finally, we pass the $node object through to the drupal_json_output() function. If you go to node/1/json you should just see outputted JSON code.

image.png

function ww_json_example_endpoint($node) {
  drupal_json_output($node);
}

If you have any questions please leave a comment below.

Further Resources


来自  https://www.webwash.net/getting-started-with-json-in-drupal-7/




Step 1 Create A Module.

It should go without saying but I find many of those asking for help on ajax are not sure what to do with all the hooks and such necessary to implement an ajax callback. So here it is from the beginning. If you know how to create a module already, skip this step or copy the code for a fully functional example module.

Create a folder in the path “/sites/all/module/custom/” called “ajax_example”. All paths are relative to the Drupal installation root usually something like: /var/www/html/sitename

In that folder create an info file named “ajax_example.info” and paste the following code into that file exactly as listed:

  1. name = AJAX Example
  2. description = An ajax callback example.
  3. project = Custom
  4. core = 7.x

This information will be displayed in the Drupal modules page.

Create a couple empty files named “ajax_example.module” and “ajax_example.js”. Just leave them as empty files for now.

Step 2 Set up the menu hook

Open the ajax_example.module file in your favorite code editor.

Set up a url of the ajax callback by implementing Drupal's hook_menu. This is how Drupal will pass information to javascript. Create the menu hook by pasting this code into the ajax_example.module file:

  1. /**
  2.  * Implements hook_menu().
  3.  */
  4. function ajax_example_menu() {
  5.  

  6.   // Ajax Callback. Returns telephone number for current region.
  7.   $items['ajax/username'] = array(
  8.     'title' => 'Get Current User Name',
  9.     'page callback' => 'ajax_example_get_username',
  10.     'access arguments' => array('access content'),
  11.     'type' => MENU_CALLBACK,
  12.   );
  13.  

  14.   return $items;
  15. }

Drupal’s hook_menu defines url’s for the system. The array offset ‘ajax/username’ is the actual url the ajax code will call. The page callback is the function that will retrieve the information. The rest of these options can be researched at api.drupal.org.

Step 3 Create the callback function

Next task is to return the information the ajax call wants. Still in our module file, create the function named in the page callback.

  1. /**
  2.  * AJAX function that returns the current logged in users name.
  3.  */
  4. function ajax_example_get_username() {
  5.  

  6.   // Get currently logged in user.
  7.   global $user;
  8.   $user_name = $user->name;
  9.  

  10.   // Drupal 7 Old School.
  11.   print $user_name;
  12.   drupal_exit();
  13.  

  14.   // Drupal 7 New School.
  15.   drupal_json_output($user_name);
  16.  

  17.   // Drupal 6.
  18.   print $user_name;
  19.   module_invoke_all('exit');
  20.   exit;
  21. }

This function varies a bit from Drupal 6 and Drupal 7 so both are included. Only use the code that is associated with your version of Drupal.

First the function retrieves the information. In this example it’s just the currently logged in users name. But any information can obtained. The function can run raw queries, pull globals, generate entire pages, or just return some random text.

The return is the important piece. Do not try to send the data with a return statement. Drupal assumes that information called by a menu hook is a page. Any information returned will be wrapped with the default page template. This is usually not desired for an ajax function.

So instead pass the info to jQuery with a standard “print”. Also note that even if the function does not return a value if the function returns at all the page template will be printed to the screen by the menu system. In order to prevent the page template from being outputted the function should be exited stopping any further html generation. The exit is a little different in Drupal 6 and 7. Several clean-up tasks are good to perform before killing Drupal.  In Drupal 6 these clean-up tasks are signaled with a call to “module_invoke_all(‘exit’)”. This just calls any exit hooks implemented on the current Drupal system. The function drupal_exit in Drupal 7 calls the hook invoke and the php exit making the code a little cleaner and passing the responsibility of clean-up to Drupal’s core.

Step 4 Write your ajax function

Now for the actual ajax function. Here I am using jQuery as it makes ajax and javascript much easier to work with. Like the exit functions above Drupal 6 and 7 differ slightly in how they implement jQuery files. Paste the appropriate code snippet for your version of Drupal into the .js file created earlier.

Drupal 6

  1. Drupal.behaviors.ajax_example = function (context) {
  2.  

  3.   // If the site name is present set it to the username.
  4.   if ($('#site-name', context).length) {
  5.     $.ajax({
  6.       url: '/ajax/username',
  7.       success: function(data) {
  8.         // Change site name to current user name.
  9.         $('#site-name a span').html(data + '.com');
  10.      }
  11.     });
  12.   }
  13. }

Drupal 7

  1. (function ($) {
  2.   Drupal.behaviors.ajax_example = {
  3.     attach:function (context) {
  4.  

  5.       // If the site name is present set it to the username.
  6.       if ($('#site-name', context).length) {
  7.         $.ajax({
  8.           url: '/ajax/username',
  9.           success: function(data) {
  10.  

  11.             // Change site name to current user name.
  12.             $('#site-name a span').html(data + '.com');
  13.          }
  14.         });
  15.       }
  16.     }
  17.   }
  18. })(jQuery);

Make sure the behavior name is unique. In this case the behavior name is the name of the module “ajax_example”. In Drupal 7 the “attach: function” is used instead of the “= function” syntax. Once inside these blocks the code is the same. This code simply checks if the site name is present. If so change the site name to the current users name. Not a very practical use of ajax but this is just meant as an example.

Step 5 Load the javascript file

Once the javascript file is finished it needs to be included in the appropriate pages. This can be done through a block hook, a page hook, a node api hook, or anything that determines a page's content. Since this specific example affects all pages on the site I’m going to make the rather poor choice of adding it in the init hook. If your ajax only affects one page use a hook that specifies that page as hook_init runs on every page load and can affect overall site performance.

  1. /**
  2.  * Implementation of hook_init().
  3.  */
  4. function ajax_example_init() {
  5.  

  6.   // Drupal 6: Add our own CSS and JS to the site.
  7.   drupal_add_js(drupal_get_path('module', 'ajax_example') . '/ajax_example.js');
  8.  

  9.   // Drupal 7: Add our own CSS and JS to the site.
  10.   drupal_add_js(drupal_get_path('module', 'ajax_example') . '/ajax_example.js', array('scope' => 'footer'));
  11. }

The only difference between Drupal 6 and 7 is the scope parameter. It’s always a good idea to throw custom js in the footer. It makes sure if any 3rd party services being accessed by your callback are down the page will still loads. Also it ensures the content the js triggers on is also loaded.

Finish Up

And there you have it. Enable the module and watch your site name change to the current logged in user’s name. Of course with JavaScript you can trigger off of a button press, search box edit, select box choice, or any of the events supported in the language.

来自  https://clikfocus.com/blog/simple-ajax-example-for-drupal-6-and-7


普通分类: