在我的 JS 中,我向 bit.ly api 发送一个 get 请求以缩短 URL。问题是我需要返回 URL 以在代码中使用。
最好使用同步请求吗?事实上,使用 bit.ly 的 XHR 请求之后的任何代码都会失败,因为响应尚未返回短 URL。
bitlyXHR.onreadystatechange = function() {
if (bitlyXHR.readyState == 4) {
if (bitlyXHR.status == 200) {
var obj = JSON.parse(bitlyXHR.responseText);
// Do something
}
}
};
bitlyXHR.open("GET", "http://api.bitly.com/v3/shorten?login=&apiKey=&longUrl=" + longURL + "&format=json");
bitlyXHR.send();
// Some code here that uses the short URL
最佳答案
你可以这样做:
function doSomething(obj) {
// this does something with the result.
}
bitlyXHR.onreadystatechange = function() {
if (bitlyXHR.readyState == 4) {
if (bitlyXHR.status == 200) {
var obj = JSON.parse(bitlyXHR.responseText);
doSomething(obj);
}
}
};
bitlyXHR.open("GET", "http://api.bitly.com/v3/shorten?login=&apiKey=&longUrl=" + longURL + "&format=json");
bitlyXHR.send();
关于javascript - XMLHttpRequest 同步或异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8212775/