Cystack
Cystack

Reputation: 3561

Loading external JSON file as a javascript variable

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 ?

Upvotes: 1

Views: 1006

Answers (2)

Phrogz
Phrogz

Reputation: 303460

If the remote host does not supply JSONP or CORS, then you will need to place a server-side component on your own domain which fetches the JSON for you and serves it locally.

Upvotes: 1

Ibu
Ibu

Reputation: 43850

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.
}

Upvotes: 1

Related Questions