Been trying to create a simple JSONP call but it doesn't always work and I dunno why. Here's the code:
server-side (http://server/server.php
):
<?php
$res = json_encode("It works!");
if(isset($_GET['callback']) === TRUE) {
header('Content-Type: text/javascript;');
header('Access-Control-Allow-Origin: http://client');
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
echo $_GET['callback']."(".$res.");";
} else {
echo $res;
}
?>
client-side (http://client/client.html
):
<html>
<head><title>JSONP</title></head>
<body>
<h1>JSONP Experiment</h1>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function process(data) {
$('#result').text(data);
}
$.getJSON(
'http://server/server.php?callback=?',
{'callback': 'process'}
);
</script>
<p id="result"></p>
</body>
</html>
This code works and displays "It works!" in my
block.
Why isn't it working when I dont use
{'callback': 'process'}
and put ?callback=process straight into the $.getJSON() URL?Why isn't it working if I use
<script src="http://server/server.php?callback=process"></script>
instead of the $.getJSON() call?
Both not-working cases actually return process("It works");
but this isn't executed, why?
Thanks