I thought this question would be trivial but I just can't seem to find an answer. A website (different origin, no control over it) is making available some JSON files. I want some variables of my script to grab the content of those files. I don't care whether it is done synchrnously or not. How would you go ?
-
1You could use jsonp? en.wikipedia.org/wiki/JSONP or jQuery way api.jquery.com/jQuery.ajaxbenqus– benqus2012-05-18 17:48:04 +00:00Commented May 18, 2012 at 17:48
-
As far as I know there is none for the browser. From JavaScript of corse.benqus– benqus2012-05-18 17:49:50 +00:00Commented May 18, 2012 at 17:49
-
JSONP is some kind of a hack, and my request seems so ... simple and pertinent. Can't believe we don't have that yet :(Cystack– Cystack2012-05-18 17:51:37 +00:00Commented May 18, 2012 at 17:51
-
Yea, I know, and since JS debuggers run in the browser it easy to hack it also, so ir doesn't make any sense at all sometimes. =) But you have no other choice except using flash... =DDD Below guy answered your question. =)benqus– benqus2012-05-18 17:53:59 +00:00Commented May 18, 2012 at 17:53
-
1@Cystack the reason you cannot just make an ajax call to a different domain is for security measures.Ibu– Ibu2012-05-18 17:55:05 +00:00Commented May 18, 2012 at 17:55
|
Show 1 more comment
2 Answers
using JSONP consist of using your url, with parameters, and add a script file to your page
www.example.com/process?value=1&callback=Func
add the script to your page.
var url = "www.example.com/process?value=1&callback=Func";
var script = document.createElement('script');
script.type= ' text/javascript';
script.src = url;
document.getElementsByTagName("body")[0].appendChild(script);
now you can use the call back function or access the variables that were added from this script.
UPDATE
At the end of your jsonp script you can call your call back function Ex: php
<?php
if (isset($_GET['callback'])) {
echo $_GET['callback']."();";
// Func(); // will call your function and use your variables.
}
4 Comments
Cystack
Thanks... JSONP is the way then... And now if I host it on my server, what would the snippet be ?
Cystack
This implies that I have control over the "example.com" server... and I don't !
Ibu
@Cystack you said "now if I host it on my server" so i thought you had control over it. in that case you will have to read the documentation of the api you are using.
benqus
You don't need JSONP if you host it on your own server. A simple async call does the job. The only thing you need is to watch for the links you make your call to. You think you are refering to your server but you can refer to it as it would seem a different domain to browsers, so watch out with that! =)