原文http://hellodrupal.info/node/149
模組檔案結構:
- sitemode.info
- sitemode.module
- test_ajax.js
sitemode.info
; $Id$name = Sitemoddescription = A content type for jokes.package = Pro Drupal Developmentcore = 6.x
sitemode.module
<?phpfunction 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;//返回表單}
test_ajax.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: '/drupal/ajax', dataType: 'json', success: function(msg){ //alert( msg); $("#main").prepend(msg.html); }, data: { 'id': $('input:radio[name=note_book]:checked').val(), }, }); }); });}
完
完