下面是自己亲自做的例子
function shipingzhongcustom_menu() {
$items = array();
$items['user_custom_pager'] = array(
'title' =>'用户自定义分页数量',
'page callback' => 'shipingzhongcustom_user_custom_pager',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function custom_pager_form()
{
global $user;
$sql = "select custom_pager from custom_zhuqutelqq_pager where uid='%d'";
$defaultValue = db_result(db_query($sql, $user->uid));
empty($defaultValue) && $defaultValue = 10;
$form['custompager'] = array(
'#type' => 'select',
'#title' => '分页数',
'#options' => array(10=>10, 20=>20, 50=>50,100=>100,200=>200,400=>400,500=>500),
'#default_value' => $defaultValue,
'#ahah' => array(
'event' => 'change',
'path' => 'user_custom_pager',
'wrapper' => 'user-dig-msg',
),
);
$form['msg']= array(
'#prefix'=>'<div id="user-dig-msg">',
'#type'=>'item',
'#suffix'=>'</div>',
);
return $form;
}
function shipingzhongcustom_user_custom_pager() {
global $user;
$custompager = $_POST['custompager']; //通过post 取值
//下面的json形式替换上面wrapper内的内容 即 $form['msg']的innerHTML的内容
//下面一定要用json的格式形式
print drupal_json(array('status' => TRUE, 'data' => '<div></div>'));
exit();
}
Drupal AHAH : AJAX异步机制(转)
本文转载自
http://community.chinahrd.net/home.php?mod=space&uid=777522&do=blog&id=166041 AHAH是Drupal6中Form Element的一个新的参数,可以通过FormElement来触发事件,提交AJAX请求。
首先要先安装 ahah helper模块 可以看看这个模块的demo演示的代码AHAH的作用域AHAH参数可被作用在以下Form Element上:
button, checkbox, image button, password, radio, select, submit, textarea, textfield
AHAH的使用
1. 为form元素增加ahah属性。
2. 配置AHAH的参数。
参数 作用
path 异步请求的路径。
wrapper 请求callback后需发生改变的DIV的ID。
method 改变wrapper这个DIV的方式,可以是replace或append。
effect 在wrapper这个DIV发生改变时的视觉效果。
progress 是否显示进度条,progress共4个配置项type、interval、url、message。
默 认情况下type是throbber(一个旋转的时钟),我们可以将type设置为bar来显示一个进度条,在interval、url不配置的情况 下,bar仅仅只会显示一个永远在滚动的虚假的进度条。message是进度条上显示的文字,url是获取进度状态的地址,progress将会异步轮询 这个地址来获取当前的进度情况,interval则是轮询间隔的时间。
例:
<?php
$form['submit']=array(
'#type'=>'submit',
'#value'=>t('Submit'),
'#ahah'=>array(
'path'=>'user_dig/export_user/js',
'wrapper'=>'user-dig-msg',
'method'=>'replace',
'effect'=>'fade',
'progress'=> array('interval'=>1000,'type'=>'bar','url'=>base_path().'user_dig/export_user/progress','message'=>t('Pleasewait...'))
),
);
?>
3. 配置一个menu来接受path的请求。
menu配置
<?php
$items['user_dig/export_user/js']=array(
'title'=>'Javascript Choice Form',
'page callback'=>'user_dig_export_user_js',
'access arguments'=> array('access content'),
'type'=>MENU_CALLBACK,
);
callback实现
function user_dig_export_user_js(){
drupal_json(array('status'=>TRUE,'data'=>theme('status_messages')));
}
?>
这时候data中的文本将会以method参数配置的方式来改变wrapper DIV中的内容。
4. 配置一个DIV做为wrapper用的DIV
wrapper用的DIV
<?php
$form['msg']= array(
'#prefix'=>'<div id="user-dig-msg">',
'#type'=>'item',
'#suffix'=>'</div>',
);
?>
5. 配置进度条状态请求的menu。 menu配置
<?php
$items['user_dig/export_user/progress']=array(
'title'=>'Javascript Choice Form',
'page callback'=>'user_dig_export_user_progress',
'access arguments'=> array('access content'),
'type'=>MENU_CALLBACK,
);
?>
callback实现:<?php
function user_dig_export_user_progress(){
//好像这里不能用 一用的话 好像数据可能出错 _drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
drupal_json(array('status'=>TRUE,'percentage'=>$_SESSION['user_dig_percentage'],'message'=>$_SESSION['user_dig_message']));
}
?>
当然这里的
$_SESSION['user_dig_percentage']
和
$_SESSION['user_dig_message']
是在path这个menucallback中计算出来的,percentage的范围是0到100。使用messsage来显示当前请求的执行阶段也是很方便的。
在这里值得注意的是似乎Drupal的ajax请求并不会完整的boot整个Drupal框架,这也就是为什么要先调用
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
来手动boot session的目的,不然对session的任何改变都不会有作用。
小结
使用AHAH可以在无需编写javascript的情况下发送AJAX请求,利用AHAH的progress的功能可以简单快捷的实显进度条。可以很容易实现提交异步form的工作。
来自 http://hi.baidu.com/fenggandeguozi/item/d4a6ed2e1cf8e3caddf69af5
drupal6 表单如何在某个元素使用ahah,并在这个表单元素中使用了自己编写的js特效?
| drupal6 表单某个元素使用ahah,并在这个表单元素中使用了自己编写的js特效,但这个表单元素经过ahah重构后,自己编写的js无法加载使用,在没有经过ahah重构之前js是起作用的,试过多种方法都不能加载自己的js,这是什么原因啊???? |
| |
2 个回答
| 具体不了解你那边的情况,这里一个例子,你可以参考下。 在#AHAH event (Drupal 6) / #AJAX event (Drupal 7) 之后 call 一个function: 1,注册地址 1
2
3
4
5
6
7
8
9
10
11
12
13
| function ahah_callback_menu()
{
return array
(
'ahah_callback' => array
(
'title' => 'AHAH callback test',
'page callback' => 'drupal_get_form',
'page arguments' => array('ahah_callback_form'),
'access arguments' => array('access content'),
),
);
}
|
2,建立form 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
| function ahah_callback_form($form_state)
{
$form = array();
// The AHAH helper module requires that the next
// function be called at the beginning of the form definition
ahah_helper_register($form, $form_state);
// First we create a wrapper to be used by the AHAH
$form['container'] = array
(
'#prefix' => '<div id="ahah_container">',
'#suffix' => '</div>',
);
// Next we add some data in this container
$form['container']['data'] = array
(
'#value' => '<p>Form element</p>',
);
// And finally we add our AHAH enabled button
$form['button'] = array
(
'#type' => 'submit',
'#value' => 'submit',
'#ahah' => array
(
// The following path is how the AHAH helper module
// registers paths. See the documentation for that
// module for more information
'path' => ahah_helper_path(array('container')),
'wrapper' => 'ahah_container',
'method' => 'append',
),
);
// We will reproduce the above form elements in order to show
// the contrast between different AHAH events later on in the
// tutorial. So we recreate the container, the data, and the button.
$form['container2'] = array
(
'#prefix' => '<div id="ahah_container2">',
'#suffix' => '</div>',
);
$form['container2']['data'] = array
(
'#value' => '<p>form element2</p>',
);
$form['button2'] = array
(
'#type' => 'submit',
'#value' => 'submit',
'#ahah' => array
(
'path' => ahah_helper_path(array('container2')),
'wrapper' => 'ahah_container2',
'method' => 'append',
),
);
return $form;
}
|
此时,您应该有一个表单可以正常运作。当点击这两个按钮,数据相关的按钮增加。注意:如果这步骤无法工作,确保您已经安装了ahah Helper模块。 现在剩下一个事情要做的,那就是添加jQuery(JavaScript)文档到我们的form。我把我的javascript加在主题函 数,Javascript的内容省略,已经超出了本讨论范围。只做一个简短的解释。现在要两步骤。第一个是注册一个主题函数使用 hook_theme(),然后第二是实现这一主题函数。 3,hook_theme() 1
2
3
4
5
6
7
8
9
10
| function ahah_callback_theme()
{
return array
(
'ahah_callback_form' => array
(
'arguments' => array('form' => NULL),
),
);
}
|
我现在已经注册函数theme_ahah_callback_form。drupal 大家应该知道是会认函数名的命名方式的,所以该函数将自动调用,并且没有什么需要被添加到表单定义。此函数传递一个变量,$form(所有form的主题函数传递这个变量)。 4,theme 函数 1
2
3
4
5
6
7
8
9
10
11
12
| function theme_ahah_callback_form($form)
{
// First we get the path to our module
$path = drupal_get_path('module', 'ahah_callback');
// Next we add the JavaScript document to the page. Note: I keep my
// JavaScript documents in a folder called 'js'. If you have your
// script in the root of the module folder, make sure to adjust your
// path accordingly
drupal_add_js($path . '/js/ahah_callback.js');
// Finally we return the rendered form.
return drupal_render($form);
}
|
确保清空缓存,否则主题函数不会进入,javascript将不会被添加。 5,然后是jQuery 我们要做的第一件事是把我们的代码在一个匿名函数套起来,传递到jQuery对象以避免名称空间冲突: 1
2
3
| (function($) {
// Our code will go in here
}(jQuery));
|
6,我们需要使用.ajaxComplete()函数。
1
2
3
4
5
6
| (function($) {
$(document).ajaxComplete(function()
{
// the code to be fired after the AHAH is completed will go here
});
}(jQuery));
|
每个AHAH事件将会回调地址。我们需要找出他们是什么,为了能够为跟踪我们想要的AHAH call。我使用以下code:
1
2
3
4
5
6
7
8
9
| (function($) {
// we need to add some variables to the ajaxComplete()
// callback function. The one we are most concerned with
// is the 3rd, 'settings'
$(document).ajaxComplete(function(e, xhr, settings)
{
alert(settings.url);
});
}(jQuery));
|
现在,当我们触发AHAH完成后,我们将得到一个javascript警告告诉我们的路径访问。对于本教程,两个按钮访问以下路径: /[path_to_webroot]/ahah_helper/container /[path_to_webroot]/ahah_helper/container2 注意:你的网站路径不同于我的目录,或可能不存在,所以要根据实际情况去做小变动。在这个的例子中,根目录是叫"sandbox"。您将看到下一代码会引用 sandbox。 最后,我们添加一个条件(或多个条件),当ahah 事件触发就会引入我们的code。 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| (function($) {
$(document).ajaxComplete(function(e, xhr, settings)
{
// button 1
if(settings.url == "/sandbox/ahah_helper/container")
{
alert("button 1 pushed");
}
// button 2
else if(settings.url == "/sandbox/ahah_helper/container2")
{
alert("button 2 pushed");
}
});
}
|
当第一个ahah按钮点击后,文本”button 1 pushed”显示在一个javascript警告。当第二个AHAH按钮点击后,文本”button 2 pushed”显示在一个javascript警告。 我希望这个教程来帮助你。祝你好运! |
来自 http://www.drupalla.com/node/1189
AHAH Example: Select control and generated checkboxes
Note that this is currently maintained in the Examples project so the code here may not be the latest.
In this example we use a select control to determine how many checkboxes are generated.
(Experience this one at http://d6.drupalexamples.info/examples/ahah_example/autocheckboxes.)
<?php
/<strong>
* @file
* A Self-configure a form based on a select control
* Add the number of checkboxes specified in the select
*/
function ahah_demo_autocheckboxes(&$form_state) {
$default = !empty($form_state['values']['howmany']) ? $form_state['values']['howmany'] : 1;
$form['howmany'] = array(
'#title' => t('How many checkboxes do you want?'),
'#type' => 'select',
'#options' => array(1=>1, 2=>2, 3=>3, 4=>4),
'#default_value' => $default,
'#ahah' => array(
'path' => 'ahah_demo/autocheckboxes/callback',
'wrapper' => 'checkboxes',
'effect' => 'fade',
),
);
$form['checkboxes'] = array(
'#title' => t("Generated Checkboxes"),
'#prefix' => '<div id="checkboxes">',
'#suffix' => '</div>',
'#type' => 'fieldset',
'#description' => t('This is where we get automatically generated checkboxes'),
);
$num_checkboxes = !empty($form_state['values']['howmany']) ? $form_state['values']['howmany'] : 1;
for ($i=1; $i<=$num_checkboxes; $i++) {
$form['checkboxes']["checkbox$i"] = array(
'#type' => 'checkbox',
'#title' => "Checkbox $i",
);
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Click Me'),
);
return
$form;
}
/</
strong>
* Callback for autocheckboxes. Process the form with the number of checkboxes
* we want to provide
*/
function ahah_demo_autocheckboxes_callback() {
$form_state = array('storage' => NULL, 'submitted' => FALSE);
$form_build_id = $_POST['form_build_id'];
$form = form_get_cache($form_build_id, $form_state);
$args = $form['#parameters'];
$form_id = array_shift($args);
$form_state['post'] = $form['#post'] = $_POST;
$form['#programmed'] = $form['#redirect'] = FALSE;
// HACK: Select values changing never get recognized
unset ($form['howmany']['#value']);
drupal_process_form($form_id, $form, $form_state);
$form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
$checkboxes = $form['checkboxes'];
$output = drupal_render($checkboxes);
// Final rendering callback.
print drupal_json(array('status' => TRUE, 'data' => $output));
exit();
}
?>
来自 http://randyfay.com/content/ahah-example-select-control-and-generated-checkboxes
下面是ahah demo 演示模块
<?php
/**
* Hi,
*
* This is a very brief tutorial of what you need to do to use the ahah_helper
* module. This piece of text is all you need to know, besides knowing the
* Forms API basics already.
*
* This is not a perfect approach to AHAH forms. But then again, the very
* reason this module exists is because Drupal 6's Forms API does an even
* worse job.
* 90% of what you know about Forms API stil applies. A few things are
* different, to make it work perfectly.
* 1) Always call ahah_helper_register() at the beginning of your form. It
* sets $form['#cache'], stores in what file the form definition function
* exists and adds some JS.
* Finally, it stores the last entered value for each form item; this
* allows you to dynamically add and remove form items and still remember
* their last entered value! The last known value for $form['foo']['bar']
* is stored in $form_state['storage']['foo']['bar].
* 2) That's it. Well, that and one change in how you write form items: you
* will *always* have to set #default_value, and *always* assign it the
* latest known value. If not, the value will be empty.
* This is an annoyance indeed, but it cannot be worked around easily. See
* the remark at the top of the ahah_helper.module file.
*
* Good luck!
*/
//----------------------------------------------------------------------------
// Drupal core hooks.
/**
* Implementation of hook_menu().
*/
function ahah_helper_demo_menu() {
$items['ahah_helper_demo'] = array(
'page callback' => 'drupal_get_form',
'page arguments' => array('ahah_helper_demo_form'),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}
//----------------------------------------------------------------------------
// Forms API callbacks.
/**
* Form definition; ahah_helper_demo form.
*/
function ahah_helper_demo_form($form_state) {
$form = array();
// Register the form with ahah_helper so we can use it. Also updates
// $form_state['storage'] to ensure it contains the latest values that have
// been entered, even when the form item has temporarily been removed from
// the form. So if a form item *once* had a value, you *always* can retrieve
// it.
ahah_helper_register($form, $form_state);
// Determine the default value of the 'usage' select. When nothing is stored
// in $form_state['storage'] yet, it's the form hasn't been submitted yet,
// thus it's the first time the form is being displayed. Then, we set the
// default to 'company'.
if (!isset($form_state['storage']['billing_info']['usage'])) {
$usage_default_value = 'company';
}
else {
$usage_default_value = $form_state['storage']['billing_info']['usage'];
}
$form['billing_info'] = array(
'#type' => 'fieldset',
'#title' => t('Billing information'),
'#prefix' => '<div id="billing-info-wrapper">', // This is our wrapper div.
'#suffix' => '</div>',
'#tree' => TRUE, // Don't forget to set #tree!
);
$form['billing_info']['usage'] = array(
'#type' => 'select',
'#title' => t('Usage'),
'#options' => array(
'private' => t('Private'),
'company' => t('Company'),
),
'#default_value' => $usage_default_value,
'#ahah' => array(
'event' => 'change',
// This is the "magical path". Note that the parameter is an array of
// the parents of the form item of the wrapper div!
'path' => ahah_helper_path(array('billing_info')),
'wrapper' => 'billing-info-wrapper',
),
);
$form['billing_info']['update_usage'] = array(
'#type' => 'submit',
'#value' => t('Update usage'),
// Note that we can simply use the generic submit callback provided by the
// ahah_helper module here!
// All it does, is set $form_state['rebuild'] = TRUE.
'#submit' => array('ahah_helper_generic_submit'),
// We set the 'no-js' class, which means this submit button will be hidden
// automatically by Drupal if JS is enabled.
'#attributes' => array('class' => 'no-js'),
);
// If 'company' is selected, then these two form items will be displayed.
if ($usage_default_value == 'company') {
$form['billing_info']['company_name'] = array(
'#type' => 'textfield',
'#title' => t('Company name'),
'#required' => TRUE,
'#size' => 20,
'#maxlength' => 255,
// If the user switched to Private usage and back to Company usage, we
// remembered his company's name!
'#default_value' => $form_state['storage']['billing_info']['company_name'],
);
$form['billing_info']['vat'] = array(
'#type' => 'textfield',
'#title' => t('VAT number'),
'#description' => t('Please enter a Belgian VAT number, the format is: <em>BE0999999999</em>.'),
'#size' => 20,
'#maxlength' => 255,
// If the user switched to Private usage and back to Company usage, we
// remembered his VAT number!
'#default_value' => $form_state['storage']['billing_info']['vat'],
'#ahah' => array(
'event' => 'blur',
'path' => ahah_helper_path(array('billing_info', 'vat')),
'wrapper' => 'edit-billing-info-vat-wrapper',
'effect' => 'none',
'method' => 'replace',
),
);
// Provide instantaneous (#ahah-powered) feedback to the user about the
// VAT number he entered.
if (isset($form_state['storage']['billing_info']['vat']) && strlen($form_state['storage']['billing_info']['vat']) > 0) {
$form['billing_info']['vat']['#field_suffix'] = theme('image', (preg_match('/^BE0\d{9}$/', $form_state['storage']['billing_info']['vat'])) ? 'misc/watchdog-ok.png' : 'misc/watchdog-error.png');
}
}
// And if 'private' is selected, then these two form items will be displayed.
else {
$form['billing_info']['first_name'] = array(
'#type' => 'textfield',
'#title' => t('First name'),
'#required' => TRUE,
'#size' => 20,
'#maxlength' => 255,
// If the user switched to Company usage and back to Private usage, we
// remembered his first name!
'#default_value' => $form_state['storage']['billing_info']['first_name'],
);
$form['billing_info']['last_name'] = array(
'#type' => 'textfield',
'#title' => t('Last name'),
'#required' => TRUE,
'#size' => 20,
'#maxlength' => 255,
// If the user switched to Company usage and back to Private usage, we
// remembered his last name!
'#default_value' => $form_state['storage']['billing_info']['last_name'],
);
}
$form['billing_info']['address'] = array(
'#type' => 'textfield',
'#title' => t('Address'),
'#required' => TRUE,
'#size' => 20,
'#maxlength' => 255,
// Always set #default_value, even if it's not a dynamically added form item!
'#default_value' => $form_state['storage']['billing_info']['address'],
);
$form['billing_info']['country'] = array(
'#type' => 'textfield',
'#title' => t('Country'),
'#size' => 20,
'#maxlength' => 255,
// Always set #default_value, even if it's not a dynamically added form item!
'#default_value' => $form_state['storage']['billing_info']['country'],
);
$form['save'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
return $form;
}
/**
* Validate callback for the ahah_helper_demo form.
*/
function ahah_helper_demo_form_validate($form, &$form_state) {
// Check the VAT number if:
// - the form item is being displayed, and
// - a VAT number has been entered (it's not a required form item)
if (isset($form['billing_info']['vat']) && strlen($form_state['values']['billing_info']['vat']) > 0) {
// Check if the entered VAT number is valid in Belgium.
if (!preg_match('/^BE0\d{9}$/', $form_state['values']['billing_info']['vat'])) {
form_error($form['billing_info']['vat'], t('Invalid VAT number.'));
}
}
}
/**
* Submit callback for the ahah_helper_demo form.
*/
function ahah_helper_demo_form_submit($form, &$form_state) {
drupal_set_message('Congratulations, you entered valid data. Unfortunately, nothing was saved because this is a demo.');
}
最简单的 AHAH 例子: 提交按钮的 #ahah, 替换一个区域
由 hooface 于 星期日, 2011-05-22 - 11:39 发表
请注意,这里的代码可能不是 Examples 项目里最新的。
AHAH本质就是,使用 AHAH 标记一个表单元素激活了 AHAH 行为,并告诉它当这个行为被激活时,哪部分 HTML 内容将被替换。
我们正在使用的表单里有一个“标记“元素,这只是普通的HTML。它有一个涉及 CSS ID 的前缀和后缀。 CSS ID 将被后台运行的 JavaScript 用于确定是什么要被替换。实际上,在调试过程中,你可以在这个路径输入到您的Web浏览器,看看有什么发生。在这里你可以将http://d6.drupalexamples.info/examples/ahah_example/simplest_ahah/callback 回调粘贴到你的浏览器地址栏,打开看看会发生什么。
当提交按钮被按下,不是做传统的HTTP提交页面,Drupal所提供的JavaScript调用回调,获取生成的HTML(作为一个JSON对象),然后使用获取的HTML 替换(指定 ID 的 div“盒子”)的内容。
(这是一致的,在http://d6.drupalexamples.info/examples/ahah_example/simplest_ahah)
这是一个非常简单的 AHAH 行为例子:
<?php
function
ahah_demo_simplest() {
$initial_markup
=
'<div style="background: lightblue; width: 150px; height: 150px">'
. t(
'This is a blue box'
) .
'</div>'
;
$form
[
'box'
] =
array
(
'#type'
=>
'markup'
,
'#prefix'
=>
'<div id="box">'
,
'#suffix'
=>
'</div>'
,
'#value'
=>
$initial_markup
,
);
$form
[
'submit'
] =
array
(
'#type'
=>
'submit'
,
'#ahah'
=>
array
(
'path'
=>
'ahah_demo/simplest_ahah/callback'
,
'wrapper'
=>
'box'
,
),
'#value'
=> t(
'Click Me'
),
);
return
$form
;
}
function
ahah_demo_simplest_callback() {
$colors
=
array
(
'red'
,
'orange'
,
'blue'
,
'green'
,
'black'
);
$color
=
$colors
[
array_rand
(
$colors
)];
$output
=
'<div id="box" style="background-color:'
.
$color
.
'; width: 150px; height: 150px;">This is '
.
$color
.
' box</div>'
;
print
drupal_json(
array
(
'status'
=> TRUE,
'data'
=>
$output
));
exit
();
}
?>