如何将数组传递给 Drupal 菜单回调

2021-12-29 00:00:00 callback php javascript ajax drupal

我在 JavaScript 中有两个数组:var xcoord = [];var ycoord = [];经过一些处理,每个数组包含 15 个数值.我想将此数据发送到 Drupal 中的菜单回调.

I have two arrays in JavaScript: var xcoord = []; and var ycoord = []; After some processing, each array contains 15 numeric values. I'd like to send this data to a menu callback in Drupal.

我的 AJAX 代码:

My AJAX code:

$.post('http://mysite.com/?q=menu_example/my_page', 
    {'ycoord[]': ycoord, 'xcoord[]': xcoord }
);

Drupal PHP:

Drupal PHP:

$items['menu_example/my_page/%/%'] = array(
    'title' => 'My Page', 
    'description' => 'i hope this works', 
    'page callback' => '_graphael', 
    'page arguments' => array(2, 3), // fill this, 
    'access callback' => true,
    'type' => MENU_CALLBACK,
);

在我的控制台中,我看到 xcoordycoord 的值正在正确传输,但回调并不完全正常.我的问题:如何将数组传递给菜单回调?我还应该在 $items 键中使用 % 占位符吗?

In my console, I see that the values for xcoord and ycoord are being properly transmitted, but the callback isn't quite working. My question: how would I pass arrays to a menu callback? Should I still use a % placeholder in the $items key ?

推荐答案

您传递给 $.post() 的第二个参数未附加到您作为第一个参数传递的 URL;它是在 $_POST 中传递给 PHP 的数据.

The second argument you pass to $.post() is not attached to the URL you pass as first argument; it is data that is passed to PHP in $_POST.

菜单回调的正确定义应如下所示.

The correct definition for the menu callback should be the following one.

$items['menu_example/my_page'] = array(
  'title' => 'My Page', 
  'description' => 'I hope this works', 
  'page callback' => '_graphael', 
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);

您的页面回调应该会在 $_POST 中找到从 jQuery 传递的数据.

Your page callback should then find the data passed from jQuery in $_POST.

相关文章