JavaScript-无法从onload函数中获取数据(http请求)
因此,我目前正在开发一个使用api的程序 我有两个功能: getBotID() 和getAuth() 我必须先获取botID,然后才能尝试获取新的AuthToken,因此我立即在getAuth()函数中调用getBotID() 我的问题是:我无法在getBotID()中的http请求的onload()函数之外获取botID,因为它将如下运行:JavaScript-无法从onload函数中获取数据(http请求),javascript,api,http,request,onload,Javascript,Api,Http,Request,Onload,因此,我目前正在开发一个使用api的程序 我有两个功能: getBotID() 和getAuth() 我必须先获取botID,然后才能尝试获取新的AuthToken,因此我立即在getAuth()函数中调用getBotID() 我的问题是:我无法在getBotID()中的http请求的onload()函数之外获取botID,因为它将如下运行: 启动getAuth() 启动getBotID() 完成getBotID() 完成getAuth() 现在完成getBotID()的onload函数 我无法
我无法从onload函数中获取botID数据。我已经试过给你一个回调函数,但是没有用。我想这会有用的。将匿名函数传递给
getBotId
,并让它在第一个请求完成后回调:
function getBotID(domain, callback) {
var url = "http://" + domain + ":8087/api/v1/botId";
idRequest.open("GET", url);
idRequest.onload = callback;
idRequest.send();
}
function getAuth(domain, user, pass) {
getBotID(domain, function() {
var botID = JSON.parse(this.responseText);
var url = "http://" + domain + ":8087/api/v1/bot/login";
body = '{"username": ' + user + ', "password": ' + pass + ', "botId": ' + botID + '}';
authRequest.open("POST", url);
authRequest.setRequestHeader("Content-Type", "application/json");
authRequest.onload = function() {
var authToken = JSON.parse(authRequest.responseText);
};
authRequest.send(JSON.stringify(body));
});
}
因此,最简单的方法是向getBotIDs idRequest.open()函数添加一个“false”参数。这将导致代码同步,并且onload()函数将在其余代码运行之前完成。您不能这样做。你应该使用承诺,不要手工构建JSON。使用
JSON.stringify
@SLaks你是说body变量吗?我试试这个!看起来很聪明,我没有想过这样使用回调,不要这样做;这将完全冻结浏览器。嗯,我还没有测试,但我正在与Electron合作,也许我可以在“登录屏幕”后启动一个新窗口。不。您需要学习如何编写异步代码。阅读
function getAuth(domain, user, pass) {
getBotID(domain);
var url = "http://" + domain + ":8087/api/v1/bot/login";
body = '{"username": ' + user + ', "password": ' + pass + ', "botId": ' + botID + '}';
authRequest.open("POST", url);
authRequest.setRequestHeader("Content-Type", "application/json");
authRequest.onload = function() {
var authToken = JSON.parse(authRequest.responseText);
};
authRequest.send(JSON.stringify(body));
}
function getBotID(domain, callback) {
var url = "http://" + domain + ":8087/api/v1/botId";
idRequest.open("GET", url);
idRequest.onload = callback;
idRequest.send();
}
function getAuth(domain, user, pass) {
getBotID(domain, function() {
var botID = JSON.parse(this.responseText);
var url = "http://" + domain + ":8087/api/v1/bot/login";
body = '{"username": ' + user + ', "password": ' + pass + ', "botId": ' + botID + '}';
authRequest.open("POST", url);
authRequest.setRequestHeader("Content-Type", "application/json");
authRequest.onload = function() {
var authToken = JSON.parse(authRequest.responseText);
};
authRequest.send(JSON.stringify(body));
});
}