card.module
drupal_add_js('jQuery(document).ready(function () {
currentRequest = $.ajax({
timeout:0,
cache: false,
url: pageUrl,
dataType: "json",
type: "GET",
success: function(data){
$("#edit-field-currency-type-und-0-value").val(data.currency);
}
});
ajax请求模块
$items['mccurr/%'] = array(
'title' => '',
'page callback' => 'ajax_currency_type',
'access arguments' => array('access content'),
'page arguments' => array(1),
'type' => MENU_SUGGESTED_ITEM,
);
function ajax_currency_type($ccode){
drupal_add_http_header('Content-Type', 'application/javascript; utf-8');
$query = "SELECT countries_country.currency
FROM countries_country
WHERE countries_country.iso2 = '".$ccode."'";
$data = db_query($query);
return drupal_json_encod($data);
}
这种方式是否正确返回json数据,否则如何在car.module中返回返回数据。
谢谢
答案 0 :(得分:1)
在您的页面回调函数中,print
drupal_json_encode
' d字符串而不是return
。
print drupal_json_encode($data);
exit;
请注意,您的模块存在安全问题,您可能需要先了解这些问题。
<?php
$items['mccurr/%'] = array(
'title' => '',
'page callback' => 'ajax_currency_type',
'access arguments' => array('access content'),
'page arguments' => array(1),
'type' => MENU_SUGGESTED_ITEM,
);
function ajax_currency_type($ccode){
drupal_add_http_header('Content-Type', 'application/javascript; utf-8');
$query = 'SELECT currency FROM countries_country WHERE countries_country.iso2 = :code'; // doesn't matter multi lines
$data = db_query($query, array(':code' => $ccode)); // Parameters, baby!
// You will probably need to fetchAllAssoc() or something to get the data in the desired format. Also try to send proper headers on empty results, etc
print drupal_json_encode($data);
exit;
}
使用此代码,您的模块将打印json编码的字符串,输出中不会有其他HTML。
请注意,这不是最好的方法。请参阅system/ajax
路径的菜单路由器定义,并注意那里的delivery callback
。