Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set my local javascript variable as a json data on remote website

I have a javascript code on my website, there is a variable:

var remoteJsonVar;

On the other hand there is a json file on a remote website

https://graph.facebook.com/?ids=http://www.stackoverflow.com

I need to set the variable remoteJsonVar to this remote jason data.

I am sure that it is very simple, but I can't find the solution.

A small working example would be nice.

like image 368
alisia123 Avatar asked Feb 19 '12 11:02

alisia123


1 Answers

Because you're trying to get the data from a different origin, if you want to do this entirely client-side, you'd use JSON-P rather than just JSON because of the Same Origin Policy. Facebook supports this if you just add a callback parameter to your query string, e.g.:

https://graph.facebook.com/?ids=http://www.stackoverflow.com?callback=foo

Then you define a function in your script (at global scope) which has the name you give in that callback parameter, like this:

function foo(data) {
    remoteJsonVar = data;
}

You trigger it by creating a script element and setting the src to the desired URL, e.g.:

var script = document.createElement('script');
script.src = "https://graph.facebook.com/?ids=http://www.stackoverflow.com?callback=foo";
document.documentElement.appendChild(script);

Note that the call to your function will be asynchronous.

Now, since you may want to have more than one outstanding request, and you probably don't want to leave that callback lying around when you're done, you may want to be a bit more sophisticated and create a random callback name, etc. Here's a complete example:

Live copy | Live source

(function() {

  // Your variable; if you prefer, it could be a global,
  // but I try to avoid globals where I can
  var responseJsonVar;

  // Hook up the button
  hookEvent(document.getElementById("theButton"),
            "click",
            function() {
      var callbackName, script;

      // Get a random name for our callback
      callbackName = "foo" + new Date().getTime() + Math.floor(Math.random() * 10000);

      // Create it
      window[callbackName] = function(data) {
          responseJsonVar = data;
          display("Got the data, <code>shares = " +
            data["http://www.stackoverflow.com"].shares +
            "</code>");

          // Remove our callback (`delete` with `window` properties
          // fails on some versions of IE, so we fall back to setting
          // the property to `undefined` if that happens)
          try {
              delete window[callbackName];
          }
          catch (e) {
              window[callbackName] = undefined;
          }
      }

      // Do the JSONP request
      script = document.createElement('script');
      script.src = "https://graph.facebook.com/?ids=http://www.stackoverflow.com&callback=" + callbackName;
      document.documentElement.appendChild(script);
      display("Request started");
  });

  // === Basic utility functions

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = msg;
    document.body.appendChild(p);
  }

  function hookEvent(element, eventName, handler) {
    // Very quick-and-dirty, recommend using a proper library,
    // this is just for the purposes of the example.
    if (typeof element.addEventListener !== "undefined") {
      element.addEventListener(eventName, handler, false);
    }
    else if (typeof element.attachEvent !== "undefined") {
      element.attachEvent("on" + eventName, function(event) {
        return handler(event || window.event);
      });
    }
    else {
      throw "Browser not supported.";
    }
  }
})();

Note that when you use JSONP, you're putting a lot of trust in the site at the other end. Technically, JSONP isn't JSON at all, it's giving the remote site the opportunity to run code on your page. If you trust the other end, great, but just remember the potential for abuse.

You haven't mentioned using any libraries, so I haven't used any above, but I would recommend looking at a good JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. A lot of the code above has already been written for you with a good library. For instance, here's the above using jQuery:

Live copy | Live source

jQuery(function($) {

  // Your variable
  var responseJsonVar;

  $("#theButton").click(function() {
    display("Sending request");
    $.get("https://graph.facebook.com/?ids=http://www.stackoverflow.com&callback=?",
          function(data) {
            responseJsonVar = data;
            display("Got the data, <code>shares = " +
              data["http://www.stackoverflow.com"].shares +
              "</code>");
          },
          "jsonp");
  });

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});
like image 107
T.J. Crowder Avatar answered Sep 20 '22 04:09

T.J. Crowder