[英]How I can return and get JSON data with Drupal 7
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 request module 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);
}
Is this way correct to return the json data else how can i get the return data back in my car.module. 以这种方式返回JSON数据是正确的,否则我如何在我的car.module中获取返回数据。
Thank You 谢谢
In your page callback function, print
the drupal_json_encode
'd string instead of return
ing it. 在页面回调函数中,
print
drupal_json_encode
字符串,而不return
它。
print drupal_json_encode($data);
exit;
Note that you module has security problems that you might need to understand first. 请注意,您的模块存在安全问题,您可能需要首先了解。
<?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;
}
With this code, your module will print the json encoded string and no other HTML will be in the output. 使用此代码,您的模块将打印json编码的字符串,并且输出中将没有其他HTML。 Note that this is no the best way to do this.
请注意,这不是执行此操作的最佳方法。 See the menu router definition of
system/ajax
path and pay attention to delivery callback
there. 请参阅
system/ajax
路径的菜单路由器定义,并注意那里的delivery callback
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.