是否有任何“正确”的方式来获得服务器的响应,而不使用JQuery/AJAX,当然没有刷新页面? server.js:如何从服务器获得响应而无需刷新和使用JQuery/AJAX?
var http = require('http');
var url = require('url');
var qs = require('querystring');
var static = require('node-static');
var file = new static.Server('.');
http.createServer(function(req, res) {
if (req.method == 'POST' && req.url == "/reglog.html") {
var body = '';
req.on('data', function (data) {
body += data;
// Destroy connection if data is too large for it
if (body.length > 1e6) {
req.connection.destroy();
}
});
req.on('end', function() {
//it's time to parse body
var post = qs.parse(body);
//send response everything is ok
if (post.email.length > 0 && post.pswrd.length > 0 && post.login.length > 0) {
//also console.log to see what was sent from client
console.log(post);
res.end('Everything is good!');
} else {
// ...or not ok
res.end('Everything is bad!');
}
});
} else if (method = 'GET') {
file.serve(req, res);
}
}).listen(8080);
所以,有reglog.js:
var xhr = new XMLHttpRequest();
var uemail = document.getElementById("email"); //HTML element for user's email
var ulogin = document.getElementById("login"); //HTML element for user's login
var upswrd = document.getElementById("pswrd"); //HTML element for user's password
var message = document.getElementById("message"); //HTML element for response from server
function hide(tout) {
if (tout === undefined) tout = 2500;
return setTimeout(function() {
message.innerHTML = "";
}, tout);
}
document.getElementById("btn").onclick = (function createUser(){
var email = uemail.value;
var login = ulogin.value;
var pswrd = upswrd.value;
//XHR part starts//
var body = "email="+email+"&login="+login+"&pswrd="+pswrd;
//I know that email, login and pswrd should be with encodeURIComponent, but in my case it's not a problem and using it won't solve my main problem
xhr.open("POST","/reglog.html",true);
xhr.send(body);
message.style.color = "black";
xhr.onload = function() {
message.innerHTML = xhr.responseText;
}
//XHR part ends//
});
document.getElementById("lbtn").onclick = (function logMenu(){
document.getElementById('logform').style.display = "block";
document.getElementById('regform').style.display = "none";
});
document.getElementById("rbtn").onclick = (function regMenu(){
document.getElementById('regform').style.display = "block";
document.getElementById('logform').style.display = "none";
});
而且reglog.html:
.button{
position: absolute;
top: 45%;
bottom: 55%;
left: 15%;
}
Register
E-mail:
Login:
Password:
Log in
Login:
Password:
正如你看到的,我可以在的客户端获得响应
但我可以看到它约0.5秒,之后会有页面刷新。这不是看结果的最好方法。我的问题:是否有可能在“跨度”中看到这个响应超过0.5秒?我的意思是,也许刷新页面,然后显示此响应?我不知道该怎么做,因为总会有响应(0.5秒),然后刷新页面。 另外我不知道如果没有AJAX/JQuery可以做到这一点。
我很高兴得到任何帮助,因为这是折磨我两天的问题,我没有通过谷歌找到任何合理的答案。