Skip to content

Commit a7a740d

Browse files
Merge pull request #259 from chernjie/master
Improved support for jsonp callbacks
2 parents b7fe4ab + 9f345f6 commit a7a740d

File tree

2 files changed

+19
-16
lines changed

2 files changed

+19
-16
lines changed

application/libraries/Format.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,24 @@ public function to_csv()
215215
// Encode as JSON
216216
public function to_json()
217217
{
218-
return json_encode($this->_data);
218+
$callback = isset($_GET['callback']) ? $_GET['callback'] : '';
219+
if ($callback === '')
220+
{
221+
return json_encode($this->_data);
222+
}
223+
// we only honour jsonp callback which are valid javascript identifiers
224+
else if (preg_match('/^[a-z_\$][a-z0-9\$_]*(\.[a-z_\$][a-z0-9\$_]*)*$/i', $callback))
225+
{
226+
// this is a jsonp request, the content-type must be updated to be text/javascript
227+
header("Content-Type: application/javascript");
228+
return $callback . "(" . json_encode($this->_data) . ");";
229+
}
230+
else
231+
{
232+
// we have an invalid jsonp callback identifier, we'll return plain json with a warning field
233+
$this->_data['warning'] = "invalid jsonp callback provided: ".$callback;
234+
return json_encode($this->_data);
235+
}
219236
}
220237

221238
// Encode as Serialized array

application/libraries/REST_Controller.php

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,7 @@ public function response($data = null, $http_code = null)
468468

469469
is_numeric($http_code) OR $http_code = 200;
470470

471+
// @deprecated the following statement can be deleted.
471472
// If the format method exists, call and return the output in that format
472473
if (method_exists($this, '_format_'.$this->response->format))
473474
{
@@ -1529,19 +1530,4 @@ protected function _check_access()
15291530
return FALSE;
15301531
}
15311532

1532-
1533-
// FORMATING FUNCTIONS ---------------------------------------------------------
1534-
// Many of these have been moved to the Format class for better separation, but these methods will be checked too
1535-
1536-
/**
1537-
* Encode as JSONP
1538-
*
1539-
* @param array $data The input data.
1540-
* @return string The JSONP data string (loadable from Javascript).
1541-
*/
1542-
protected function _format_jsonp($data = array())
1543-
{
1544-
return $this->get('callback').'('.json_encode($data).')';
1545-
}
1546-
15471533
}

0 commit comments

Comments
 (0)