Skip to content

Instantly share code, notes, and snippets.

@buzzedword
Last active December 13, 2015 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buzzedword/4946664 to your computer and use it in GitHub Desktop.
Save buzzedword/4946664 to your computer and use it in GitHub Desktop.
Using JSONP with FosRestBundle
(function($, undefined) {
var requests = {
getJsonAction : 'http://remote.domain.com/json/?callback=?' // Note the callback = ?, this automagically makes a function
};
// The function which handles the response
var responseHandler = function(data){
// Do something with the data
// ...
};
$(function(){
// JSON call to server
$.getJSON(requests.getJsonAction, {
'additional' : 'parameters'
}, responseHandler);
});
}(jQuery));
<?php
namespace Demo\Bundle\Controller;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\JsonResponse; // Helper added in Symfony 2.1 for JSON responses
class JsonController extends FOSRestController
{
public function getJsonAction()
{
$data = array(
//...
);
$callback = $this->getRequest()->get('callback'); // Check to see if callback parameter is in URL
$response = new JsonResponse(); // Construct a new JSON response
if (isset($callback))
$response->setCallback($callback); // Set callback function to variable passed in callback
$response->setData($data);
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment