2017-08-25 19 views
-1

我使用非同步的XMLHttpRequest从香草的JavaScript的浏览器扩展程序的API我提出这样的我可以在另一个函数中包装异步xmlhttprequest的回调函数吗?

function getInfo(url, callback) { 
    var xmlhttp; 
    xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState === 4 && xmlhttp.status === 200) 
      callback(xmlhttp.responseText); 
    } 
    xmlhttp.open("GET", url, true); 
    xmlhttp.send(); 
} 

我有一些选项卡,单击时我希望他们做出这样了XMLHttpRequest请求获取数据这

<div class="tab"> 
     <button class="tablinks" id = "HN" onclick="getLinks(event)"><img src=https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Y_Combinator_Logo_400.gif/100px-Y_Combinator_Logo_400.gif></button> 
     <button class="tablinks" id= "Reddit" onclick="getLinks(event)"><img class = "logo" src=https://www.observepoint.com/wp-content/uploads/2015/03/reddit-129.png></button> 
     <button class="tablinks" id= "Github" onclick="getLinks(event)"><img class ="logo" src=https://static1.squarespace.com/static/56278c08e4b07be93cfbb3aa/t/57f1de373e00bef6ad3fc3bc/1475468903021/github-logo?format=100w></button> 
    </div> 
function getLinks(evt) { 
    getInfo("https://hacker-news.firebaseio.com/v0/topstories.json", function(result) { 
     //do stuff 
    }); 
} 

当我打电话的getLinks功能,那我做些什么来改变t时的东西他的HTML从不改变。我的问题是,是否有可能把回调函数放在另一个函数里面,比如我正在做的事情?或者我以错误的方式接近它?我需要它,只有当我按下三个按钮中的一个时,它才从API中检索链接并将它们放入HTML中。有没有更好的方法让香草JS中的异步呼叫只发生在特定的行动中。我对JS很新奇。

回答

0

我的问题是,是否有可能把回调函数内的另一个功能就像我现在这样?

是的。

相关问题