How to return JSONP from a menu callback I can create JSON output using a menu hook using the drupal_json_output callback.

Example:

$items['page/%/json'] = array(
  'access callback'   =&gt; TRUE,
  'page callback'     =&gt; '_modulename_json',
  'delivery callback' =&gt; 'drupal_json_output'
);

function _modulename_json() {
  return array(
    'item1' =&gt; $field_item1[0]['safe_value'],
    'item2' =&gt; $field_item2[0]['safe_value'],
    'item3' =&gt; $item3,
    );
}


Output:

{"item1":"Field item1 content","item2":"Field item2 content","item3":"Item3 content"}


But I need to have JSONP, and am struggling to find an elegant solution... I have tried the code from the bottom of the API page, it does the padding, but makes a mess of the content.

$response = array(1,2,3);
$callback = check_plain($_REQUEST['callback']);
// If its a jsonp callback request
if (isset($callback) &amp;&amp; $callback != '') {
  $json_response = drupal_json_encode($response);
  echo $callback ."(". $json_response .");";
}
else {
  drupal_json_output($response);
}


Output this way:

callbackName({\u0022item1\u0022:\u0022Field item1 content\u0022,\u0022item2\u0022:\u0022Field item2 content\u0022,\u0022item3\u0022:\u0022Item3 content\u0022});"
The array was being double encoded. First by the $json_response = drupal_json_encode($response); and then again by the menu delivery callback 'delivery callback' =&gt; 'drupal_json_output'.

To fix this, remove the delivery callback, and use just 'type' =&gt; MENU_CALLBACK,.

In the function change this:

if (isset($callback) &amp;&amp; $callback != '') {
  $json_response = drupal_json_encode($response);
  echo $callback ."(". $json_response .");";
}


to this:

if (isset($callback) &amp;&amp; $callback != '') {
  $json_response = drupal_json_encode($response);
  drupal_add_http_header('Content-Type', 'application/javascript');
  echo $callback . "(" . $json_response . ");";
  drupal_exit();
}