后端后,渲染模板通过Flask中的Ajax从前端接收JSON

时间:2018-07-18 10:46:55

标签: python ajax flask

我试图通过Ajax接收Post quest(JSON文件)后呈现模板,但是它不起作用,除了我进入页面http://localhost:5000/distance_comuting时,它可以显示数据结果['lat'] * data ['lng']

这是我的代码

@main.route('/distance_computing', methods = ['GET','POST'])
def distance_computing():
    data = request.get_json()
    return render_template('main/test.html', result = data['lat']*data['lng'])

错误是:

Traceback (most recent call last):
  File "/Users/user/PycharmProjects/website/venv/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/user/PycharmProjects/website/venv/lib/python3.6/site-packages/werkzeug/contrib/fixers.py", line 152, in __call__
    return self.app(environ, start_response)
  File "/Users/user/PycharmProjects/website/venv/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/user/PycharmProjects/website/venv/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/user/PycharmProjects/website/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/Users/user/PycharmProjects/website/venv/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/user/PycharmProjects/website/venv/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/user/PycharmProjects/website/venv/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/user/PycharmProjects/website/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/Users/user/PycharmProjects/website/venv/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/user/PycharmProjects/website/venv/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/user/Document/Python/User.github.io/Code/app/main/views.py", line 34, in distance_computing
    return render_template('main/test.html', result = data['lat']*data['lng'])
TypeError: 'NoneType' object is not subscriptable

然后我尝试print(data)

enter image description here

第一次,它是None,然后在接收到Ajax时,它变成JSON数据。但已经使用无...呈现了模板...


<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id = 'omg'></div>
 <script type="text/javascript">
       navigator.geolocation.getCurrentPosition(function (position) {
           var pos = {
               lat: position.coords.latitude
               lng: position.coords.longitude
           };
           req = $.ajax({
               type: 'POST',
               url: 'http://localhost:5000/distance_computing',
               data: JSON.stringify(pos),
               contentType: 'application/json; charset=UTF-8',
               dataType: 'json',
               success: function (data) {
                   console.log(data);
                   $('#omg').html(data)
               },
               error: function(xhr, status, error)
           { console.log(error) }
           });
       });

    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

@main.route('/distance_computing', methods = ['GET','POST'])
def distance_computing():
  data = request.get_json() if request.get_json() is not None and request.method == "POST" else {'lat': 0, 'lng': 0}
  return render_template('main/test.html', result = data['lat']*data['lng'])

也无需使用JSON.stringify(),只需按原样发布对象即可。