javascript和html连接

lrl1mhuk  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(285)

我对html和javascript非常陌生。我为登录功能创建了一个非常简单的html页面。代码如下。

<html>
    <head>
        <body>
            <form>
                <p>Username</p>
                <input type='text' name="" placeholder="Enter Username/Email ID">
                <p> Password</p>
                <input type='password' name="" placeholder="Enter Password">
                <input type='submit' name="" value="LogIn the User">
            </form>         
        </body>
    </head>
</html>

现在我有了一个具有登录功能的restful api。我可以在postman中以json格式发送用于api测试的用户名和密码值。

现在我的问题是如何将登录api的其余部分与html页面连接起来。如果这是一个重复的问题,那么请把我带到原来的问题。另外,如果你能建议一些资源。我经历了很多,但找不到相关的。谢谢

pinkon5k

pinkon5k1#

基本步骤是
截取表单上的提交事件
解析表单以创建要提交的json
提交json
对回应做点什么

document.forms[0].addEventListener('submit', function(e) { // when they submit
    e.preventDefault(); // Don't try and submit the form the traditional way
    const data = {
        username: e.target.querySelector('input[name="username"]').value,
        password: e.target.querySelector('input[name="password"]').value
    } // get the JSON we want to submit
    fetch('/auth/login', {
        method: 'post', // submit it as a post request
        body: JSON.stringify(data)
    }).then(function(response) {
        return response.json(); // parse the response as json
    }).then(function(data) {
        console.log('do something with the response');
    });
});
<html>
    <head>
        <body>
            <form>
                <p>Username</p>
                <input type='text' name="username" placeholder="Enter Username/Email ID">
                <p> Password</p>
                <input type='password' name="password" placeholder="Enter Password">
                <input type='submit' value="LogIn the User">
            </form>         
        </body>
    </head>
</html>

相关问题