我有以下代码,问题是chrome.tabs.getSelected的回调是在使用空url发送的请求之后计算的。我该如何解决这个问题?
function send() {
var url = '';
chrome.tabs.getSelected(null, function(tab) {
url = tab.url;
});
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
if(this.readyState == 4) {
alert(this.status);
}
}
client.open("POST", "http://myurl");
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(url);
}
答案 0 :(得分:6)
欢迎使用异步编程
function send() {
chrome.tabs.getSelected(null, function(tab) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
if(this.readyState == 4) {
alert(this.status);
}
}
client.open("POST", "http://myurl");
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(tab.url);
});
}