Я собрал несколько JavaScript кодов из различных источников, отредактировал их и заставил работать.
Проблема в том, что я не понимаю части кода и мне нужна помощь понимание этих частей.
По сути, код отправляет имя пользователя и пароль в горячую точку, ожидает 0,5 se c и отправляет вводимые пользователем сообщения на веб-сервер.
Что мне трудно понять, так это resolve("fast");
. Является ли быстрое внутреннее восстановление только потому, что для разрешения требуется «аргумент / параметр», поскольку он никогда не отображается?
Кроме того, в какой-то момент мой код получил ...
reject({
status: this.status,
statusText: xhr.statusText
});
.. и я получил ошибку. Само собой разумеется, я не понимаю, что и где именно должны отображаться status
и statusText
.
Много кода, который я получил от Stack Overflow и Developer.Mozilla.Org.
Спасибо за помощь.
JS код
document.getElementById("submit_ok").addEventListener("click", sendAjax);
function resolveAfter05Second() {
console.log("starting fast promise")
return new Promise(resolve => {
setTimeout(function() {
resolve("fast")
console.log("fast promise is done")
}, 500)
})
}
async function sendAjax() {
let ax1 = await Ajax1 ("POST", "http://router/login")
let fast = await resolveAfter05Second()
let ax2 = await Ajax2 ("POST", "http://webserver/anti-xss.php")
}
function Ajax1 (method, url){
return new Promise (function (resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://router/login', true);
xhr.onload = function(){
if(this.status >= 200 && this.status < 300){
resolve(xhr.response);
console.log("Success!");
console.log("You'r logged in.");
console.log("XHR1 " + xhr.readyState);
console.log("XHR1 " + xhr.status);
}else{
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function (){
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send("username=HSuser&password=SimpleUserPassword");
});
}
function Ajax2 (method, url){
return new Promise (function (resolve, reject){
let xhr2 = new XMLHttpRequest();
xhr2.open('POST', 'http://webserver/anti-xss.php', true);
xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr2.onload = function(){
if(this.status >= 200 && this.status < 300){
resolve(xhr2.response);
console.log("Success!");
console.log("You'r email is " + useremail + ".");
console.log("XHR2 " + xhr2.readyState);
console.log("XHR2 " + xhr2.status);
}else{
reject({
status: this.status,
statusText: xhr2.statusText
});
}
};
xhr2.onerror = function (){
reject({
status: this.status,
statusText: this.statusText
});
};
let useremail = document.getElementById("email").value;
xhr2.send("Email="+encodeURIComponent(useremail));
});
}