Javascript 如何将res从一个函数传递到另一个函数?
我创建了这个小的FB.api调用,它返回一些数据。现在,我想在访问localhost:8080/test时显示这些数据,我该怎么做?这样做的方法是什么?有人能告诉我一些可能的文档吗?首先,您可以在这样的快速路线中添加您的FB.api调用Javascript 如何将res从一个函数传递到另一个函数?,javascript,node.js,Javascript,Node.js,我创建了这个小的FB.api调用,它返回一些数据。现在,我想在访问localhost:8080/test时显示这些数据,我该怎么做?这样做的方法是什么?有人能告诉我一些可能的文档吗?首先,您可以在这样的快速路线中添加您的FB.api调用 FB.api('4', function (res) { if(!res || res.error) { console.log(!res ? 'error occurred' : res.error); return; } consol
FB.api('4', function (res) {
if(!res || res.error) {
console.log(!res ? 'error occurred' : res.error);
return;
}
console.log(res.id);
console.log(res.name);
});
// viewed at http://localhost:8080
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
然后在index.html中,您可以向页面添加一些javascript,并创建一个XHR来调用“localhost:8080/something”
index.html
app.get('/something', function(req, res) {
FB.api('4', function (result) {
if(!res || res.error) {
return res.send(500, 'error');
}
res.send(result);
});
});
var xhr=new XMLHttpRequest();
xhr.open('GET','http://localhost:8080/something');
xhr.onreadystatechange=函数(){
if(xhr.readyState==4){
var data=xhr.responseText;
//用这些数据做任何你想做的事情。
}
}
xhr.send();
嵌套调用FB.api
在app.get
中(您需要将res
重命名为FBres
以避免与app.get
res
冲突),然后在FB.api
回调中读取FBres
,然后写入res
,瞧。还有:@csharpfolk很好,谢谢!不是没有Csharp但是你知道你的东西!谢谢你的链接,还有什么好的文档可以推荐吗?谢谢,伙计,这是为我做的。你推荐什么好的文档?我不知道你需要什么样的文档,但是你可以访问他们的api有一个可靠的文档,如果你需要更多关于XHR的信息,我建议你访问mozilla获取文档还有这篇文章,你可以在html5rocks上找到,非常酷谢谢,这就是我一直在寻找的。
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/something');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var data = xhr.responseText;
//Do whatever you want with this data.
}
}
xhr.send();
</script>