[英]Ajax Vanilla JS - ajax async continuing without waiting for readyState 4, status 200
TLDR:我想等待第一个请求完成,然后再继续第二个请求等。
你好,
我目前正在处理 HotSpot 页面。 用户需要输入他的电子邮件,瞧! 他可以上网。
是应该在后台发生的事情,就是当用户把他的电子邮件和印刷机发送;
然后 js/html 页面等待来自路由器的 readyState === 4 (DONE) 响应,
然后 js/html 页面等待 DONE 响应
这基本上就是应该发生的事情。 实际发生的是,JS 不会等待 readyState === 4 和 Status === 200。一旦用户单击 Submit,他就会立即被重定向。
我不能使用 JQuery,因为路由器 (Mikrotik) 出于自己的目的使用 $。
用F12工具检查网络后,我可以看到POST到路由器的状态为200,并且携带正确的参数(用户名=HSuser&password=SimpleUserPassword),我可以看到POST到服务器的状态为200 并且还有正确的参数(电子邮件地址,即:Email=Ba%40loo.ns)。
我想我的 JS 代码有点错误,因为它不等待。
此外,在摆弄代码后的一些共鸣,没有更多的电子邮件插入数据库(它们之前是,不知道现在是什么问题。)
下面是当前的代码。 我还会发布一个以前的版本(它也不起作用),以防有人可以在那里发现问题。
如果有人需要任何其他信息,请告诉我。
谢谢你。
编辑 3 。:
我继续阅读 Stack Overflow,我偶然发现了这条信息......
服务器负责提供
status
,而用户代理提供readyState
。
这是自动完成的服务器端,还是我需要以某种方式实现它?
编辑 1 。:
我在这里试过控制台日志
if (xhr.readyState === DONE){
console.log("XHR1" + xhr.readyState);
console.log("XHR1" + xhr.status);
if (xhr.status === OK){
和这里
if (xhr2.readyState === DONE){
console.log("XHR2" + xhr2.readyState);
console.log("XHR2" + xhr2.status);
if (xhr2.status === OK){
我只有XHR1 (XHR14 和 XHR1200),我没有从XHR2得到任何东西。
编辑2 。:
尝试用 onload 替换 onreadystatechange,仍然做同样的事情。
当前的 HTML 代码:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html" />
<meta charset="utf-8" />
<title>HotSpot</title>
</head>
<body>
<!-- Email form which is saved into the DB -->
<form accept-charset="utf-8" name="mail" onsubmit="return false;" method="post" id="mail">
<h1>Hotspot</h1>
<h2>To gain internet access, enter your email.</h2>
<br />
<input type="text" id="email" name="email" autofocus="autofocus" />
<br />
<input type="submit" value="Submit" id="submit_ok" name="submit_ok" /> <br />
</form>
<script type="text/javascript">
document.getElementById("submit_ok").addEventListener("click", SendAjax);
function SendAjax() {
var email = document.getElementById("email").value;
console.log(email);
// Check if fields are empty
if (email=="") {
alert("Please enter your email.");
}
// AJAX code to submit form
else{
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://router/login', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
xhr.onreadystatechange = function () {
var DONE = 4;
var OK = 200;
if (xhr.readyState === DONE){
if (xhr.status === OK){
var xhr2 = new XMLHttpRequest();
xhr2.open('POST', 'http://server/insertDB.php', true);
xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
var useremail = document.getElementById("email").value;
xhr2.onreadystatechange = function () {
if (xhr2.readyState === DONE){
if (xhr2.status === OK){
location.href = "http://server/redirected.html";
}
}
}
}
xhr2.send("Email="+encodeURIComponent(useremail));
}
}
xhr.send("username=HSuser&password=SimpleUserPassword");
}
};
</script>
</body>
</html>
当前的 PHP 代码:
<?php
require ('connect.php');
$clean_email = "";
$cleaner_email = "";
if(isset($_POST['email']) && !empty($_POST['email'])){
//sanitize with filter
$clean_email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
//sanitize with test_input
$cleaner_email = test_input($clean_email);
//validate with filter
if (filter_var($cleaner_email,FILTER_VALIDATE_EMAIL)){
// email is valid and ready for use
echo "Email is valid";
//Email is a column in the DB
$stmt = $DB->prepare("INSERT INTO addresses (Email) VALUES (?)");
$stmt->bind_param("s", $cleaner_email);
$stmt->execute();
$stmt->close();
} else {
// email is invalid and should be rejected
echo "Invalid email, try again";
}
} else {
echo "Please enter an email";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$DB->close();
?>
以前的 HTML/JS 代码:
function SendAjax() {
var email = document.getElementById("email").value;
console.log(email);
// Check if fields are empty
if (email=="") {
alert("Please enter your email.");
}
// AJAX code to submit form
else{
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://router/login', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
xhr.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (xhr.readyState === XMLHttpRequest.DONE){
var xhr2 = new XMLHttpRequest();
xhr2.open('POST', 'http://server/insertDB.php', true);
xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
var useremail = document.getElementById("email").value;
xhr2.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (xhr2.readyState === XMLHttpRequest.DONE) {
location.href = "http://server/redirected.html";
}
};
xhr2.send("Email="+encodeURIComponent(useremail));
}
}
xhr.send("popup=true&username=HSuser&password=SimpleUserPassword");
}
}
如果它使您的生活更轻松(并且会),您可以将 jQuery 置于无冲突模式。
<!-- Putting jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
var $j = jQuery.noConflict();
// $j is now an alias to the jQuery function; creating the new alias is optional.
$j(document).ready(function() {
$j( "div" ).hide();
});
// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
var mainDiv = $( "main" );
}
</script>
https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/
然后你可以进行 AJAX 调用,应该等待的东西可以进入成功函数:
$j.ajax({
url: '/your-form-processing-page-url-here',
type: 'POST',
data: yourVariables,
mimeType: 'multipart/form-data',
success: function(data, status, jqXHR){
alert('Hooray! All is well.');
console.log(data);
console.log(status);
console.log(jqXHR);
},
error: function(jqXHR,status,error){
// Hopefully we should never reach here
console.log(jqXHR);
console.log(status);
console.log(error);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.