jquery - 我如何从 jquery ajax 向 Flask View 发送 POST 请求?

标签 jquery python json ajax flask

希望您度过愉快的一天:D 让我开始解释我要做的事情:我有一个 html 页面 (index.html) 和一个 View (/index),index.html 页面中包含一个表单,在提交时将使用 jquery ajax 发送 json反对/index View 这是非常简单明了的index.html 的代码:

<body>
<form action="/" method='post'>
    <button id='submit'>submit</button>
</form>

<script src="../static/jquery.min.js"></script>
<script>
    function saveMenu() {
        localStorage.setItem("shoppingMenu", JSON.stringify(
            [{"name":"*Kabab Combo Plate","price":10.99,"count":4},
            {"name":"Mixed Grill(Lamb, Chicken, Kefta)","price":14.99,"count":4}]
            ));
    };

    saveMenu();

    function loadMenu() {
        menu = JSON.parse(localStorage.getItem("shoppingMenu"));
        return menu;
    };
</script>
<script>
    $(document).ready(function() {
        var menu = JSON.stringify(loadMenu());
        $('#submit').click(function(){
            $.ajax({
                data: menu,
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                url: '{{ url_for("index") }}',
                success: function(m){
                        console.log(m);
                },
                error: function(m){
                    console.log(m);
                }
            });
        });
    });
</script>
</body>

这是/index View 的代码,请注意我添加了打印语句,这是出于调试目的,您很快就会明白我的意思:

@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        data = request.json
        print('header: ', request.headers.get('Content-Type'))
        print('data type: ', type(data))
        print('data = ', data)
        for i in data:
            print(i)
        return 'success'
    return render_template('index.html')

现在执行前面的代码时会发生什么:

* Debugger is active!
* Debugger PIN: 143-889-961
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [24/Oct/2017 21:12:20] "GET / HTTP/1.1" 200 -
header:  application/json; charset=UTF-8
data type:  <class 'list'>
data =  [{'name': '*Kabab Combo Plate', 'count': 4, 'price': 10.99}, {'name': 'Mixed Grill(Lamb, Chicken, Kefta)', 'count': 4, 'price': 14.99}]
{'name': '*Kabab Combo Plate', 'count': 4, 'price': 10.99}
{'name': 'Mixed Grill(Lamb, Chicken, Kefta)', 'count': 4, 'price': 14.99}
127.0.0.1 - - [24/Oct/2017 21:12:24] "POST / HTTP/1.1" 200 -
header:  application/x-www-form-urlencoded
data type:  <class 'NoneType'>
data =  None
127.0.0.1 - - [24/Oct/2017 21:12:24] "POST / HTTP/1.1" 500 -
Traceback (most recent call last):
  File "C:\Users\Orbit\flaskname\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\Orbit\flaskname\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\Orbit\flaskname\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Orbit\flaskname\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Orbit\flaskname\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Orbit\flaskname\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\Orbit\flaskname\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Orbit\flaskname\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Orbit\flaskname\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\Orbit\flaskname\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\Orbit\flaskname\app\hello.py", line 25, in index
    for i in data:
TypeError: 'NoneType' object is not iterable
127.0.0.1 - - [24/Oct/2017 21:12:24] "GET /?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [24/Oct/2017 21:12:24] "GET /?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [24/Oct/2017 21:12:24] "GET /?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [24/Oct/2017 21:12:24] "GET /?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
127.0.0.1 - - [24/Oct/2017 21:12:24] "GET /?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -

通过查看打印语句输出,在错误出现之前,请注意 request.json 工作正常并返回我们期望的数据,但随后出现 127.0.0.1 - - [24/Oct/2017 21:12:24] “POST/HTTP/1.1” 200 - 显示出来,然后看起来 View 函数正在重新运行自身,然后打印语句不输出任何内容作为数据变量的值...有谁知道为什么会发生这种模式?以及如何解决它?

最佳答案

问题是,默认情况下,表单中的提交事件(在本例中,当您单击提交按钮时发生)将重定向到表单的 action,如下所示这样,您实际上正在执行两个请求(ajax 和默认请求)。

要防止出现这种情况,请在点击处理程序内触发 event.preventDefault(并将 event 添加到参数中)。

.click(function(event) {
  // ...
  event.preventDefault()
}

您还需要从 Flask View 返回一个 json 响应,如下所示:

from flask import jsonify

# ...

  return jsonify('success')

关于jquery - 我如何从 jquery ajax 向 Flask View 发送 POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46917518/

相关文章:

javascript - 更改时内部函数的 jQuery 回调

jquery - 按字母顺序显示下拉值

python - API FedEx express "INVALID.INPUT.EXCEPTION","message":"Invalid field value in the input"

python - python 中的战舰游戏

javascript - 从 PHP 返回的变量中获取值

javascript - 链接在悬停时跳跃

javascript - jQuery - 单选按钮单击()

python - Django ;无法上传图片且表单数据无效

java - "2017-09-11 14:28:42"的 Json 反序列化失败,显示 'while it seems to fit format ' yyyy-MM-dd'T'HH :mm:ss. SSS'Z '''

javascript - 如何在 React js 中插入 json 数据?