如何在远程网站上将我的本地javascript变量设置为json数据

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

本文关键字:javascript 我的 变量 设置 数据 json 程网站 网站      更新时间:2023-09-26

我的网站上有一个javascript代码,有一个变量:

var remoteJsonVar;

另一方面,远程网站上有一个json文件

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

我需要将变量remoteJsonVar设置为此远程jason数据。

我确信这很简单,但我找不到解决办法。

一个小的工作例子会很好。

因为您正试图从不同的来源获取数据,如果您想完全在客户端执行此操作,您应该使用JSON-p,而不仅仅是JSON,因为同源策略。如果你只需在查询字符串中添加一个callback参数,Facebook就支持这一点,例如:

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

然后,您在脚本中定义一个函数(在全局范围内),该函数的名称与您在callback参数中给出的名称相同,如下所示:

function foo(data) {
    remoteJsonVar = data;
}

您可以通过创建script元素并将src设置为所需的URL来触发它,例如:

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

请注意,对函数的调用将是异步

现在,由于您可能希望有多个未完成的请求,并且可能不想在完成后留下回调,因此您可能需要更复杂一点,并创建一个随机回调名称等。以下是一个完整的示例:

实时副本|实时源

(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.";
    }
  }
})();

请注意,当您使用JSONP时,您对另一端的站点非常信任。从技术上讲,JSONP根本不是JSON,它为远程站点提供了在页面上运行代码的机会。如果你信任另一端,那就太好了,但要记住虐待的可能性。

您没有提到使用任何库,所以我没有使用任何上述库,但我建议您查看一个好的JavaScript库,如jQuery、Prototype、YUI、Closure或其他任何库。上面的许多代码已经用一个好的库为您编写了。例如,上面使用jQuery:

实时副本|实时源

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);
  }
});