Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  159] [ 1]  / answers: 1 / hits: 15408  / 12 Years ago, thu, march 1, 2012, 12:00:00

What do I need to on the server side to allow someone to get data from that server using JSONP. And what do I need to do on the user side as well? I want to use JSONP as an alternative to an XMLHttpRequest.



It won't work out of my Firefox extension, because of the same-origin policy. So, people recommended JSON, but I am pretty lost after searching for tutorials and guides on the internet.



Thanks for the help!


More From » json

 Answers
7

Assuming your server is running PHP, you just need to add 'callback' GET request.



<?php header('content-type: application/json; charset=utf-8');
$data = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo $_GET['callback'] . '('.json_encode($data).')';


And on client side (using jQuery):



$.ajax({url: 'http://site.com/data.php', dataType:'jsonp'});


The PHP code above is just for demo, don't forget to sanitise $_GET['callback']



That said, if your issue just the same origin policy, you'll probably just need to allow cross-origin from the server side, and everything should work.


[#87108] Wednesday, February 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elainaw

Total Points: 83
Total Questions: 99
Total Answers: 111

Location: South Sudan
Member since Sat, May 27, 2023
1 Year ago
;