Уроки Базовые ajax запросы в Drupal

X-ray

Шустроган
Старейшина
Токенов DAPF
140.42
Репутация
Добавить в /sites/all/module/ новый модуль demo.
В demo.info напишем:
Код:
name = Demo
description = Демо ajax request.
core = 7.x
В demo.module добавим:
Код:
/**
 * @file
 * Demo module, Basic Ajax request.
 */
 
/**
 * Implements hook_menu().
 */
function demo_menu()
{
    return array(
        'demo/page' => array(
            'page callback' => 'demo_page_callback',
            'access callback' => TRUE,
            'type' => MENU_CALLBACK,
        ),
        'demo/ajax' => array(
            'page callback' => 'demo_ajax_callback',
            'access callback' => TRUE,
            'type' => MENU_CALLBACK,
            'delivery callback' => 'demo_ajax_delivery_callback',
        ),
    );
}
 
/**
 * Demo page callback.
 */
function demo_page_callback()
{
    $path = drupal_get_path('module', 'demo');
    drupal_add_js($path . '/demo.js');
 
    $output = '<p>This is an ajax demo link: ';
    $output .= l('Click me ! ', 'demo/page',
                      array(
                           'fragment' => 'nojs',
                           'attributes' => array('id' => array('demo-ajax-link'))
                      )
    );
    $output .= '</p>';
 
    return $output;
}
 
/**
 * Demo Ajax callback.
 */
function demo_ajax_callback()
{
    $response = array(
        'status' => 1,
        'data' => 'Hello ! ',
    );
 
    return drupal_json_output($response);
}
По клику на ссылку выведем в консоль результат запроса:
Код:
(function ($) {
    Drupal.behaviors.ajax_example = {
        attach:function (context) {
            $("#demo-ajax-link").click (function() {
                $.ajax({
                    url: 'demo/ajax',
                    success: function(data) {
                        console.log(data)
                    }
                });
            });
        }
    }
})(jQuery);
 

Похожие темы

Сверху