10.24 2017-06-08 22:52 采纳率: 0%
浏览 64

Flask的Ajax问题

For the past few days I have been attempting to get an ajax call to work with Flask. No matter what I try nothing is working. So I will jump right into my code:

Python Code:

 @app.route("/num")
 def num():
     return render_template('num.html')

 @app.route('/add_num', methods=['POST'])
 def add_num():
    a = request.form['a']
    b = request.form['b']
    a = int(a)
    b = int(b)
    print(a)
    if a and b:
      c = a + b 
      return jsonify(result = c)
    return jsonify({'error' : 'Missing Data'})

HTML Code

  <form>
     <input id='a' type="text" size="5" name="a"/> +
     <input id='b' type="text" size="5" name="b"/> =
     <br>
     <br>
     <button>Add It!</button>
  </form>

  <h1 id='result'>Result</h1>

Ajax Code:

     <script type="text/javascript">
       $(document).ready(function(){
          $('form').bind('submit', function(event){
            $.ajax({
               data: {
                  a: $('#a').val(),
                  b: $('#b').val()
               },
               type: 'POST',
               url: '/add_num',
               dataType: 'json',
               data: JSON.stringify(json),
               contentType: 'application/json;charset=UTF-8'
           })
            .done(function(data){
              if (data.error){
                $('#result').text(data.error).show();
              }else{
                $('#result').text(data.result).show();
              }
           });
        event.preventDefault();
        });
       });
      </script>

When I hit the submit button nothing happens. I will see this in the URL: http://127.0.0.1:5000/num?a=2&b=3 Also, at one point I was getting the numbers added but taken to a separate page that showed JSON information. To have that happen my top line of my form was this:

    <form action='add_num' method="post" role='form'>

Now I have tried to use a different format of ajax which works perfectly fine in my code. However, I want to try this method because I like it much better. I am fairly certain that the solution is something simple but I cannot track it down. Any help would be great!

This is what finally got it working for me:

`  $(document).ready(function(){
     $('form').bind('submit', function(event){
        event.preventDefault();
           $.ajax({
               data: {
                  a: $('#a').val(),
                  b: $('#b').val()
           },
            type: 'POST',
            url: '/add_num',
            success: function(data){
            $('#result').text(data.result).show();
        }
     });
   });
  });`
  • 写回答

1条回答

  • weixin_33709609 2017-06-08 23:19
    关注

    Move event.preventDefault() above your ajax call. If you saw a and b in the parameter string, that means the form is performing its default action.

    EDIT: It could be that you two data keys in the object you're passing to $.ajax and that on the second data key you're calling JSON.stringify with a variable that doesn't seem to exist as a parameter.

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名