【发布时间】:2018-12-05 14:41:22
【问题描述】:
在我的项目中,我需要通过自定义 API 在数据库中注册一个用户(POST 请求)。
一旦该操作完成,我想发出 GET 请求以获取所有用户并将新创建的信息(例如 id 和其他信息)传递到下一个状态(我正在使用 Phaser 框架开发游戏)。
我想要做的是在发布请求中使用回调来调用另一个函数来再次检索所有玩家,但它当然不起作用,因为它们是异步操作(虽然我认为我可以通过回调解决)。
这是我的两个功能:
saveNewUser: function(name, password){
var self = this;
if(name && password){
// create new calibration data for the current user
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://project.herokuapp.com/api/users",true);
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var input = JSON.stringify({
"name": name,
"password": password,
});
xhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
self.retrieveNewUser(name);
}
};
xhttp.send(input);
} else {
self.errorMessage.visible = true;
// make text become not visible again after few seconds
self.time.events.add(Phaser.Timer.SECOND * 3, function () {
self.errorMessage.visible = false;
}, this);
}
}
以及内部调用的函数:
retrieveNewUser: function (name) {
var self = this;
// save user details in the global variables, get user after registration in db
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://duchennegame.herokuapp.com/api/users', true);
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
var userFound = false;
users.forEach(function(user){
if(user.name === name){
// save user details in the global variables
self.game.global.currentUser = user;
self.state.start('welcome');
userFound = true;
}
});
// if user has not been found / wrong password, display error message
if(!userFound){
self.errorMessage.setText('Problem in retrieving the current user');
self.errorMessage.visible = true;
// make text become not visible again after few seconds
self.time.events.add(Phaser.Timer.SECOND * 3, function () {
self.errorMessage.visible = false;
}, self);
}
} else {
console.error(users);
}
};
xhr.send(null);
}
如何确保 GET 请求仅在 POST 完成后才执行?
编辑
我意识到这段代码永远不会执行,所以连控制台消息都没有打印出来:
xhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xhttp.readyState == XMLHttpRequest.DONE && xhttp.status == 200) {
console.log(xhttp.responseText);
self.retrieveNewUser(name);
}
};
但是,在this page 中,他们提供了一个以这种方式编写的示例。有什么我遗漏的吗?
【问题讨论】:
-
“不起作用”到底是什么意思? 任何事情会发生吗?是否报告错误?您在浏览器“网络”控制台中看到了什么?
-
@Pointy 基本上创建了用户,但它从不调用retrieveNewUser 函数
-
它是否记录 XHR 响应文本?控制台有错误吗?
标签: javascript post get xmlhttprequest