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();
        }
     });
   });
  });`

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.