'What setCallback is used for in Laravel json response
I am going through a Laravel tutorial on how to build a simple API. But I dont understand what the setCallback() is used for and how?
Eg:
public function index()
{
$data = Input::get('data');
If ( $data == ''){
// query DB get all results
}else{
// query DB and get specific result
}
return Response::json(array(
'error' => false,
'stores' => $data->toArray()),
200
)->setCallback(Input::get('callback'));
}
The ->setCallback(Input::get('callback')); part
Solution 1:[1]
setCallback is not necessary. It's an optional feature for supporting JSONP requests in an API intended to be used by cross-domain JavaScript.
Solution 2:[2]
It's usually used for Jsonp support. For example with request parameter
callback=jsonp_e3bb6459d76a30
->setCallback(Input::get('callback')); ->
->setCallback(jsonp_e3bb6459d76a30);
Then you response
{"result":"","message":"","code":0} will be converted to
/**/jsonp_e3bb6459d76a30({"result":"","message":"","code":0});
It will also change the response Content-type header to text/javascript; charset=UTF-8
Further more, you can check the source code for what it really do in the background.
// ...\vendor\symfony\http-foundation\JsonResponse.php
public function setCallback($callback = null)
{
if (null !== $callback) {
// partially taken from https://geekality.net/2011/08/03/valid-javascript-identifier/
// partially taken from https://github.com/willdurand/JsonpCallbackValidator
// JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details.
// (c) William Durand <[email protected]>
$pattern = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*(?:\[(?:"(?:\\\.|[^"\\\])*"|\'(?:\\\.|[^\'\\\])*\'|\d+)\])*?$/u';
$reserved = [
'break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', 'for', 'switch', 'while',
'debugger', 'function', 'this', 'with', 'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', 'extends', 'super', 'const', 'export',
'import', 'implements', 'let', 'private', 'public', 'yield', 'interface', 'package', 'protected', 'static', 'null', 'true', 'false',
];
$parts = explode('.', $callback);
foreach ($parts as $part) {
if (!preg_match($pattern, $part) || \in_array($part, $reserved, true)) {
throw new \InvalidArgumentException('The callback name is not valid.');
}
}
}
$this->callback = $callback;
return $this->update();
}
protected function update()
{
if (null !== $this->callback) {
// Not using application/javascript for compatibility reasons with older browsers.
$this->headers->set('Content-Type', 'text/javascript');
return $this->setContent(sprintf('/**/%s(%s);', $this->callback, $this->data));
}
// Only set the header when there is none or when it equals 'text/javascript' (from a previous update with callback)
// in order to not overwrite a custom definition.
if (!$this->headers->has('Content-Type') || 'text/javascript' === $this->headers->get('Content-Type')) {
$this->headers->set('Content-Type', 'application/json');
}
return $this->setContent($this->data);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ceejayoz |
| Solution 2 | LF00 |
