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

这里的技术是共享的

You are here

Drupal ajax jquery 简单应用

shiping1 的头像

Drupal ajax jquery 简单应用

 
 

Drupal结合ajax可以实现很多特出的功能,ajax功能强大,客户体验效果好。
因此比较流行。简单实用ajax来调用生成好的drupal form.
主要使用到hook menu drupal_get_form 还有hook_form

<?php

function sitemod_menu() {// 建立一个模块 sitemod
 
$items = array();
 
$items['ajax'] = array(
   
'page callback' => 'sitemod_callback_ajax',
   
'access arguments' => array('access content'),
   
'type' => MENU_CALLBACK,
  );
 
$items['test/ajax'] = array(//调用form效果 见下图
   
'page callback' => 'drupal_get_form',
   
'page arguments' => array('get_ajax_form'),// 得到定义好的表单
   
'access arguments' => array('access content'),
   
'type' => MENU_CALLBACK,
  );
  return
$items;
}

function
get_ajax_form(){//返回form选选项
 
drupal_add_js(drupal_get_path('module', 'sitemod') . '/test_ajax.js');//加载js文件
 
$form['note_book'] = array(
   
'#type' => 'radios',
   
'#title' => t('选择分类'),
   
'#default_value' => 'IBM',
   
'#options' => array(t('IBM'), t('Dell'), t('Sony'),t('HP')),
   
'#description' => t('选择你喜欢的品牌'),
  );
   return 
$form;
}

function
sitemod_callback_ajax() {
$id = $_POST['id']; //ajax post数据
switch($id){
  case
0:
   
drupal_json(array('html' => drupal_get_form('ibm_form')));//josn数据。form
    
exit;
     break;
  case
1:
  
drupal_json(array( 'html' => drupal_get_form('dell_form')));
      exit;
     break;
}

}



function
ibm_form(){//定义表单
 
$form['ibm'] = array(
 
'#type' => 'checkboxes',
 
'#title' => t('IBM最新型号电脑'),
 
'#default_value' => array('T410'),
 
'#options' => array(
   
'T400' => t('T400'),
   
'T410' => t('T410'),
   
'X200' => t('X200'),
   
'X201' => t('X201'),
   
'T410S' => t('T410S'),
  ),
 
'#description' => t('选择你喜欢的IBM型号'),
   );
   
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => t('保存选择的信息'),
   
'#weight' => 40,
  );
    
$form_state['redirect'] = 'test/view';
return
$form;
}

function
dell_form(){//定义表单
 
$form['dell'] = array(
 
'#type' => 'checkboxes',
 
'#title' => t('Dell电脑'),
 
'#default_value' => array('d1'),
 
'#options' => array(
   
'd1' => t('d1'),
   
'd2' => t('d2'),
   
'd3' => t('d3'),
  ),
 
'#description' => t('选择你喜欢的dELL型号'),
   );

     
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => t('保存选择的信息'),
   
'#weight' => 40,
  );

return
$form;//返回表单
}
?>

js文件

  if(Drupal.jsEnabled) {

      $(document).ready(function () {
        $('input:radio[name=note_book]').click(function () {
          var getSubmit = function(data) {
            $('#footer').html(data.html);
          }
        $.ajax({
          type: 'POST',
          url: '/ajax',
           dataType: 'json',
          success: getSubmit,
          data: {
  'id': $('input:radio[name=note_book]:checked').val(),

  },
        });
  
      });
      });
}

评论

 

为何不用#ahah呢?

为何不用#ahah呢?

 

:-)

:-) 只是学习测试,恩,楼上说的对,#ahah实现起来更加方便简单

来自 http://hellodrupal.info/node/149


普通分类: