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个回答


event.preventDefault()</ code>移动到ajax调用上方。 如果在参数字符串中看到 a </ code>和 b </ code>,则表示表单正在执行其默认操作。</ p>

编辑:可能是您要传递给 $。ajax </ code>的对象中的两个 data </ code>键,以及第二个 data </ code上的键 >键,您正在使用一个似乎不作为参数存在的变量调用 JSON.stringify </ code>。</ p>
     </ div>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问