Created
September 7, 2011 14:28
-
-
Save cowboy/1200708 to your computer and use it in GitHub Desktop.
JSONP "callback" param explanation, via basic PHP script.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?PHP | |
# JSONP "callback" param explanation, via basic PHP script. | |
# | |
# "Cowboy" Ben Alman | |
# http://benalman.com/ | |
# Set $data to something that will be serialized into JSON. You'll undoubtedly | |
# have your own code for this. | |
$data = array("some_key" => "some_value"); | |
# Encode $data into a JSON string. | |
$json = json_encode($data); | |
# If a "callback" GET parameter was passed, use its value, otherwise null. Note | |
# that "callback" is a defacto standard for the JSONP function name, but it may | |
# be called something else, or not implemented at all. For example, Flickr uses | |
# "jsonpcallback" for their API. | |
$jsonp_callback = isset($_GET['callback']) ? $_GET['callback'] : null; | |
# If a JSONP callback was specified, print the JSON data surrounded in that, | |
# otherwise just print out the JSON data. | |
# | |
# Specifying no callback param would print: {"some_key": "some_value"} | |
# But specifying ?callback=foo would print: foo({"some_key": "some_value"}) | |
print $jsonp_callback ? "$jsonp_callback($json)" : $json; | |
?> |
I actually used this in my Simple PHP Proxy script, but forgot it here!
<?PHP
$is_xhr = strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
header('Content-type: application/' . ($is_xhr ? 'json' : 'x-javascript'));
?>```
Not that it really matters*
, but the official JavaScript MIME type is application/javascript
nowadays (not application/x-javascript
) as per RFC4329.
*
Browsers don’t care about the Content-Type
header in this case.
thankyou, myproblem solved
mathiasbynens thanks 💯 it's proper solution. For me works.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don’t forget to send the appropriate
Content-Type
header! I’ve been using something like this for my JSON/JSONP needs:Made this into a gist with more comments: https://gist.github.com/mathiasbynens/5547352