[英]Javascript xmlhttp send api requests from forms
我有一台本地运行的服务器,该服务器具有内置的rest api。 要通过此api登录,我们需要通过POST方法将用户名,密码和组织作为参数通过POST方法发送到url localhost:8090 / ehr / api / v1 / login,服务器返回一个auth令牌作为响应。 当我尝试直接执行此操作而没有用户通过以下代码从表单输入时:
<html>
<body>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8090/ehr/api/v1/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=admin&password=admin&organization=123456");
</script>
</body>
</html>
它工作得很好,并且auth令牌作为json返回,但是如果我尝试通过以下代码通过用户表单输入执行相同的操作:
<html>
<body>
<form method="POST">
<input type="text" name="username" id="username" placeholder="Username">
<input type="password" name="password" id="password" placeholder="Password">
<input type="text" name="organization" id="organization" placeholder="Organization">
<button id="submit" onclick="login()">Let me in!</button>
<br><br>
</form>
<script type="text/javascript">
function login() {
var user=document.getElementById("username").value;
var pass = document.getElementById("password").value;
var org = document.getElementById("organization").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8090/ehr/api/v1/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param = "username="+user+"&password="+pass+"&organization="+org;
xhttp.send(param);
}
</script>
</body>
</html>
此代码引发错误
login.html:26 XHR failed loading: POST "http://localhost:8090/ehr/api/v1/login"
第二个代码出了什么问题以及如何纠正?
以这种方式发送您的参数
xhttp.send('username = user&password = pass&organization = org');
我自己弄清楚了,我只是从html中删除了表单标签,而是使用了简单的输入标签。 这可能解决了问题,可能是因为提交时的表单尝试加载新页面而不是停留在同一页面上,但是这些参数旨在从原始页面获取。 每次单击提交按钮都会加载新页面,因此无法实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.