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

I have a javascript code on my website, there is a variable:var remoteJsonVar;On the other hand there i

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

/?ids=

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.

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./?ids=http://www.stackoverflow.

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.

Share Improve this question edited Feb 19, 2012 at 11:49 alisia123 asked Feb 19, 2012 at 11:40 alisia123alisia123 3651 gold badge8 silver badges17 bronze badges 1
  • What is a "JSON script"? – Lightness Races in Orbit Commented Feb 19, 2012 at 11:46
Add a ment  | 

1 Answer 1

Reset to default 6

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./?ids=http://www.stackoverflow.?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./?ids=http://www.stackoverflow.?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 plete 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."].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./?ids=http://www.stackoverflow.&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, remend 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 remend 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./?ids=http://www.stackoverflow.&callback=?",
          function(data) {
            responseJsonVar = data;
            display("Got the data, <code>shares = " +
              data["http://www.stackoverflow."].shares +
              "</code>");
          },
          "jsonp");
  });

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745586726a4634584.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信