简体   繁体   English

接收来自 AJAX POST 请求的响应

[英]Receive response from AJAX POST request

How can I receive the response from my AJAX POST request to a URL?如何从我的 AJAX POST 请求接收到 URL 的响应?

Here is my code:这是我的代码:

<script>
    var form = document.getElementById('login-form');
    form.onsubmit = function (e) {
        e.preventDefault();
        var user = form.email.value;
        var pass = form.pass.value;
        console.log(user);
        console.log(pass);
        $.ajax({
            type: "POST",
            url: "http://localhost:5000/auth/login",
            data: {
                username: user,
                password: pass
            },
            success: function(result) {
                alert('msg');
            },
            error: function(result) {
                alert('msg');
            }
        });
        form.reset();
    };
</script>

I get the username and password when the user submits a form, which sends a POST request to the URL.当用户提交表单时,我会获取用户名和密码,该表单向 URL 发送 POST 请求。

If the POST request is successful (ie, if the server received a request) it will send a JSON with "login success" message.如果 POST 请求成功(即,如果服务器收到请求),它将发送带有“登录成功”消息的 JSON。

I'm having trouble even displaying this response message, as nothing is being displayed after I submit the form.我什至无法显示此响应消息,因为在我提交表单后没有显示任何内容。

Try adding success to your ajax request.尝试为您的 ajax 请求添加成功。

success: function (msg) {
  console.log(msg)
}

Use JSON.parse(msg) before alert the response because Ajax response is aa json在警告响应之前使用 JSON.parse(msg) 因为 Ajax 响应是一个 json

done: function (msg) {
           alert(JSON.parse(msg))
        },
        fail: function (msg) {
              alert(JSON.parse(msg))
        },
        always: function(msg) {
              alert(JSON.parse(msg))
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM