首页 > 解决方案 > 通过 POST 进行身份验证后,我需要使用 Ajax 进行 GET

问题描述

我正在尝试创建一个仪表板,该仪表板登录到 API,然后刷新某些完全自动化的数据元素。我可以登录并进行身份验证,但在谷歌搜索后不确定如何在“POST”之后“链接”GET 请求

我已经尝试观看一些 youtube 教程并创建函数,将它们附加到按钮和 div,但我无法让数据显示。第一批代码完成并登录正常,但随后就停在那里并超时。我尝试只添加第二个打开并使登录同步,但它失败了

<script type="text/javascript">
    const xhr = new XMLHttpRequest();
    var data = 'username=user&password=password';

    xhr.onreadystatechange = function()
    {
        if (xhr.readyState == "4")
    {
            if (xhr.status == "200")
            {
                console.log(xhr.responseText);
            }

            if (xhr.status = "404")
            {
            console.log("FnF");
            }

        }
    }
    xhr.open('post','https://apiServer:8443/api/login', true)
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
    xhr.setRequestHeader("Accept", "application/xml")
    //xhr.open('get', 'https://apiServer:8443/api/resource/items', true);
    xhr.send();

我希望登录在幕后完成并且不可见,并且只是让 GET 请求在 div 中显示数据(当我首先让数据工作时,我会尝试整理 xml 响应)。

标签: javascriptajaxapixmlhttprequest

解决方案


在您的代码中,您永远不会使用您的data变量:

const xhr = new XMLHttpRequest();
var data = 'username=user&password=password';

xhr.onreadystatechange = function()
{
    if (xhr.readyState == "4")
    {
        if (xhr.status == "200")
        {
            console.log(xhr.responseText);
        }

        if (xhr.status = "404")
        {
        console.log("FnF");
        }

    }
}
xhr.open('post','https://apiServer:8443/api/login', true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.setRequestHeader("Accept", "application/xml")
//xhr.open('get', 'https://apiServer:8443/api/resource/items', true);
xhr.send(data); // <====== HERE

推荐阅读