简体   繁体   English

ajax json向烧瓶发送请求

[英]ajax json post request to flask

I am struggling to send a ajax post request but cannot figure out where i am going wrong, i have this form which i submit with js and along with that form i want to send the id of a div: 我正在努力发送ajax发布请求,但无法弄清楚我要去哪里,我有使用js提交的这份表格,以及我想发送div ID的表格:

<script type="text/javascript">
      $(document).ready(function() {
        $('input[type=radio]').on('change', function() {
            $(this).closest("form").submit();
            var poll_id = $(this).closest("div").attr("id");
            var data = {poll_id};
            console.log(JSON.stringify(data));
            $.ajax({
                url: '/poll',
                type: 'POST',
                data: JSON.stringify(data),
                contentType: 'application/json',
                dataType: 'json'
              }, function(data) {
                  console.log(data);
                });
          });
    });
    </script>

and in flask i try to request it with request.get_json() but keep getting error 400, the form and db.commit() works fine: 在长颈瓶中,我尝试使用request.get_json()请求它,但不断出现错误400,该表单和db.commit()正常运行:

@app.route('/poll', methods=['GET', 'POST'])
def poll():
    polltodb = pollingresult(request.form['points'])
    session['points_session'] = request.form['points']
    db.session.add(polltodb)
    db.session.commit()
    data = request.get_json()
    print data

but the get_json() fails. 但是get_json()失败。

$(this).closest("form").submit(); tells your html page to submit the form. 告诉您的html页面提交表单。 If any javascript after that line even executes you'd be making a separate XHR request (eg 2 requests, the data would never be in the same request using this approach). 如果该行之后的任何javascript甚至执行,您都将发出一个单独的XHR请求(例如2个请求,使用这种方法,数据将永远不在同一请求中)。 To accomplish what you're trying to do I'd take a different approach: 为了完成您要执行的操作,我将采用其他方法:

  1. Add a hidden element to your form. 将一个隐藏的元素添加到您的窗体。 eg <input type="hidden" name="poll_id" id="myHiddenField"> 例如<input type="hidden" name="poll_id" id="myHiddenField">

  2. Update your javascript: 更新您的JavaScript:

     <script type="text/javascript"> (function(){ $('input[type=radio]').on('change', function () { $('#myHiddenField').val($(this).closest("div").attr("id")); $(this).closest("form").submit(); }); }); </script> 
  3. Then, access the data through the form as you normally would and don't worry about get_json() 然后,像往常一样通过表单访问数据,不必担心get_json()

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

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