我正在尝试进行基本的ajax登录,但是对于我的生活,我无法弄清楚当我执行toString()时,uname和pword变量为什么会继续打印[object HTMLInputElement]
You can see a working example here
只需输入内容并点击登录即可。它将命中数据库,然后打印出用户名,密码,然后打印服务器响应
<script>
function login() {
var xmlhttp;
var uname = "";
var pword = "";
var date;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
uname = document.getElementById("username").toString();
pword = document.getElementById("password").toString();
date = new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString();
xmlhttp.open("GET", "login.php?uname=" + uname.toString() + "&pword=" + pword.toString() + "&date=" + date, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("response").innerHTML = uname.toString() + "<br/>" + pword.toString() + "<br/>" + date + "<br/>" + xmlhttp.responseText;
}
}
}
</script>
这是HTML代码
<body>
<center>
<div style="align-content:center">
<form>
<br />
<br />
<br />
<br />
<h1 style="font-family:'Microsoft Yi Baiti'; font-size:40px">Ajax test Site</h1>
<br />
<label>Username</label>
<br />
<input type="text" id="username" name="username" style="width:190px"/>
<br />
<label>Password</label>
<br />
<input type="password" id="password" name="password"style="width:190px"/>
<br />
<label id="tryAgainText" style="color:red; visibility:hidden">Username or Password incorrect</label>
<br />
<input onclick="login()" type="button" name="submit" value="Login" style="width:216px; margin-left: 0px;"/>
</form>
<p id="response">This is the response field</p>
</div>
</center>
</body>
答案 0 :(得分:2)
您正在选择html元素来代替其中的值。应该是这个
uname = document.getElementById("username").value.toString();
pword = document.getElementById("password").value.toString();
答案 1 :(得分:2)
您需要选择代替html元素的值。
你需要使用.value。
<script>
function login() {
var xmlhttp;
var uname = "";
var pword = "";
var date;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
uname = document.getElementById("username").value.toString();
pword = document.getElementById("password").value.toString();
date = new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString();
xmlhttp.open("GET", "login.php?uname=" + uname.toString() + "&pword=" + pword.toString() + "&date=" + date, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("response").innerHTML = uname.toString() + "<br/>" + pword.toString() + "<br/>" + date + "<br/>" + xmlhttp.responseText;
}
}
}
</script>
答案 2 :(得分:1)
您必须使用.value
代替.toString()
。 .toString()
仅尝试将Object转换为字符串表示形式。
var uname = document.getElementById("username").value;
var pwd = document.getElementById("password").value;
另一种方法是使用FormData
。
var formData = new FormData(document.forms[0]);
xmlHttp.send(formData);