【问题标题】:Javascript xmlhttp send api requests from formsJavascript xmlhttp 从表单发送 api 请求
【发布时间】:2018-04-17 20:09:27
【问题描述】:

我有一个本地运行的服务器,它有一个内置的 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>

它工作得非常好,身份验证令牌作为 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"

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

【问题讨论】:

    标签: javascript html rest api xmlhttprequest


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      以这种方式发送你的参数

      xhttp.send('username=user&password=pass&organization=org');

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-28
        • 1970-01-01
        • 2015-08-08
        相关资源
        最近更新 更多