簡體   English   中英

Javascript XMLhttp從表單發送API請求

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM