复制代码代码如下:
<?php
function module_name_form() {
$form = array();
$form['city'] = array(
'#title' => t('City'),
'#type' => 'textfield',
'#autocomplete_path' => 'example/autocomplete',//--调用的路径
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Save',
);
return $form;
}
//--定义路径
function module_name_menu() {
$items['example/autocomplete'] = array(
'page callback' => '_module_name_autocomplete', //--调用数据
'access arguments' => array('access example autocomplete'),
'type' => MENU_CALLBACK
);
return $items;
}
//--从数据库读取返回数据
function _module_name_autocomplete($string) {
$matches = array();
// Some fantasy DB table which holds cities
$query = db_select('cities', 'c');
// Select rows that match the string
$return = $query
->fields('c', array('city'))
->condition('c.city', '%' . db_like($string) . '%', 'LIKE')
->range(0, 10)
->execute();
// add matches to $matches
foreach ($return as $row) {
$matches[$row->city] = check_plain($row->city);
}
// return for JS
drupal_json_output($matches); //--json格式返回
}
?>