asp.net 如何解决这个问题波纹管?JavaScript/ AJAX 问题

ca1c2owp  于 2023-08-08  发布在  .NET
关注(0)|答案(1)|浏览(89)

你好,我正在做一个asp net core应用程序,它使用 AJAX 和login.js将数据传输到我的API,但是当我试图在浏览器中执行JSON.stringify(formData)时,我得到了错误消息Uncaught ReferenceError:formData没有定义在:1:16我尝试了很多东西来修复这个问题有人能帮忙吗?

function logar(event) {
    event.preventDefault();

    var formData = {
        email: $("input[name='email']").val(),
        password: $("input[name='password']").val()
    };

    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=UTF-8",
        data: JSON.stringify(formData),
        url: "https://localhost:7291/api/User",
        success: function (result) {
            // Lógica de sucesso
        },
        error: function (error) {
            // Lógica de erro
        }
    });
};

字符串
这是我的页面

@model SquadManager.Models.UserViewModel
@{
    Layout = null;
}
<link href="~/css/login.css" rel="stylesheet" />

<section>
    <h1>Autenticação</h1>
<form>
        <input type="email" id="email" name="email" value="@Model.Email" placeholder="Username/e-mail" />
        <input type="password" id="password" name="password" value="@Model.Password" placeholder="Senha" />
        <a href="#">Esqueceu a senha?</a>

        <button type="submit" onclick="logar(event);">Login</button>
</form>

    <label>Não tem um conta?  <a href="#">Crie sua conta aqui!</a> </label>
</section>

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/login.js"></script>


页面结果错误console error

vawmfj5a

vawmfj5a1#

正如James解释的那样,我不能从函数logar中调用JSON.stringify(formData),所以我将函数logar改为下面的代码,它在表单的onsubmit事件中工作

$('form').on('submit', function (event) {
    event.preventDefault();

    var formData = {
        email: $("input[name='email']").val(),
        password: $("input[name='password']").val()
    }

    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=UTF-8",
        data: JSON.stringify(formData),
        url: "https://localhost:7291/api/User",
        success: function (result) {
            if (result.response == "ok")
                alert("Logado")
            else
                alert("Credenciais Inválidas")
        },
        error: function (error) {
            console.log(error);
        }
    })
});

字符串
the result

相关问题