0

卡片模块

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中获取返回数据。

谢谢你

4

1 回答 1

1

在您的页面回调函数中,print使用drupal_json_encode'd 字符串而不是returning 它。

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那里。

于 2013-06-28T16:49:40.820 回答