Javascript xmlhttp从表单

时间:2017-11-05 16:18:09

标签: javascript html rest api xmlhttprequest

我有一台本地运行的服务器,它有一个内置的rest api。要通过此api登录,我们需要通过POST方法将用户名,密码和组织作为参数发送到url localhost:8090 / ehr / api / v1 / login,服务器返回一个身份验证令牌作为响应。当我尝试通过以下代码直接执行此操作而无需用户输入表单:

<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"

第二个代码有什么问题以及如何纠正它?

2 个答案:

答案 0 :(得分:0)

以这种方式发送你的参数

xhttp.send(&#39;用户名=用户安培;密码= PASS&安培;组织=组织&#39);

答案 1 :(得分:0)

我自己想通了,我只是从html中删除了form标签,而是使用了简单的输入标签。这解决了问题可能是因为提交时的表单尝试加载新页面而不是停留在同一页面上,但参数旨在从原始页面获取。每次点击提交按钮时都会加载新页面,这是无法实现的。