如何将我的本地javascript变量设置为远程网站上的json数据
我的网站上有一个javascript代码,有一个变量:
I have a javascript code on my website, there is a variable:
var remoteJsonVar;
另一方面,远程网站上有一个json文件
On the other hand there is a json file on a remote website
https://graph.facebook.com /?ids=http://www.stackoverflow.com
我需要将变量 remoteJsonVar 设置为这个远程杰森数据。
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.
因为你试图从不同的来源获取数据,如果你想完全在客户端这样做,你可以使用 JSON-P 而不是因为同源政策而只是JSON。如果您只是在查询字符串中添加回调
参数,Facebook支持此功能,例如:
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
然后在脚本中定义一个函数(在全局范围内),该函数具有您在 callback
参数中给出的名称,如下所示: / p>
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;
}
您可以通过创建脚本来触发它
元素并将 src
设置为所需的URL,例如:
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:
(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,它为远程站点提供了在页面上运行代码的机会。如果你相信另一端,那很好,但要记住滥用的可能性。
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.
你没有提到使用任何库,所以我没有使用任何上面的,但我建议你看看一个很好的JavaScript库,比如 jQuery , Prototype , YUI ,关闭,或其中任何一个。上面的很多代码已经为你编写了一个很好的库。例如,以上是使用jQuery:
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:
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);
}
});