简体   繁体   English

使用 Ajax 发出 POST 请求

[英]Making POST request using Ajax

I want to send email to my flask server using Ajax but its not working.我想使用 Ajax 向我的 Flask 服务器发送电子邮件,但它不起作用。
Below is my Code.下面是我的代码。
Script:脚本:

    <script type="text/javascript">
        $(document).ready(function(){
            var email = "";
         $("#letter").on("click",function(){
             email = $("letterEmail").val();
            $.ajax({
                type: 'POST',
                url: '/letters',
                data: JSON.stringify({Email: email}),
                contentType: 'application/json;charset=UTF-8'

            });
            $("#lettersForm").html("Sent");
            console.log(email.toString());
        });
        });
        </script>

Python View to handle this: Python 视图来处理这个:

    @app.route("/letters", methods = ['POST'])
    def letters():
        email = request.json['Email']
        send_email("myemail@example.com","Email",str(email))
        return True


This is the html for the form这是表单的html

    <form id = "lettersForm">
                <div class="row uniform 50%">
                    <div class="8u 12u(mobilep)">
                        <input type="email" name="email" id="letterEmail" placeholder="Email Address" />
                    </div>
                    <div class="4u 12u(mobilep)">
                        <input id = "letter" type="submit" value="Sign Up" class="fit" />
                    </div>
                </div>
            </form>

The problem is data is not sent from client side.问题是数据不是从客户端发送的。
So I also get a KeyError on server side.所以我在服务器端也得到了一个KeyError
Please help.请帮忙。

The KeyError is due to Flask not finding the key. KeyError是由于 Flask 没有找到密钥。 Note if stringify finds an empty email variable it will not include that key in the post automatically.请注意,如果 stringify 找到一个空的电子邮件变量,它不会自动在帖子中包含该键。

Also, do not use request.json directly, but instead use request.get_json() .另外,不要直接使用request.json ,而是使用request.get_json()

The client-side problem here is in this line:这里的客户端问题在这一行:

email = $("letterEmail").val();

It will try to get any Element in the page with the tagName letterEmail , and I don't think you have it.它将尝试使用 tagName letterEmail获取页面中的任何 Element ,我认为您没有。

Probably, what you want to do here is to get it the Element by its ID:可能,您在这里要做的是通过其 ID 获取 Element:

email = $("#letterEmail").val();

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

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