How to Pass Arrays to Drupal Menu Callbacks

2019-05-22 11:42发布

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.

My AJAX code:

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

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,
);

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 ?

1条回答
Summer. ? 凉城
2楼-- · 2019-05-22 12:28

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,
);

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

查看更多
登录 后发表回答