Flask没有从jQuery请求数据中获取任何数据

Posted

技术标签:

【中文标题】Flask没有从jQuery请求数据中获取任何数据【英文标题】:Flask not getting any data from jQuery request data 【发布时间】:2012-08-04 02:34:28 【问题描述】:

我有一个 URL 处理程序,

@app.route("/", methods=['POST'])
@crossdomain(origin='*')
def hello():
    ss=str(request.data)
    print ss
    return ss

处理程序无法检索请求的数据部分。使用 jQuery 时:

jQuery.ajax(
   
      type: "POST",
      dataType: "json",
      data:"adasdasd",
      url: 'http://127.0.0.1:5000/',
      complete: function(xhr, statusText)
        alert(xhr.responseText) )

什么都不返回

【问题讨论】:

umm 也许返回了一些东西,但你没有用它做任何事情 尝试使用ajax的成功函数并根据需要操作数据success(data, textStatus, jqXHR)Function, Array A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. 但我正在使用 alert(xhr.responseText) 对其进行测试,responseText 中没有任何内容 如果你想知道参数里面的内容打印出console.log(arguments).. 它会给你对象内部的属性.. 但是如果你想处理data 里面的成功功能 是的,我这样做了,响应文本是'' 【参考方案1】:

有趣,事实证明,如果数据是使用烧瓶无法处理的 mimetype 发布的,您只能使用 request.data,否则它是一个空字符串 "" 我认为,文档不是很清楚,我做了一些测试,似乎是这样,您可以查看运行我的测试时烧瓶生成的控制台输出。

传入的请求数据

数据 包含传入的请求数据作为字符串,以防它带有 Flask 无法处理的 mimetype。

取自http://flask.pocoo.org/docs/api/

但是由于我们正在使用 json 执行标准 POST flask 可以很好地处理这个问题,因此您可以从标准 request.form 访问数据,这个 ss=str(request.form) 应该可以解决问题,因为我已经测试过了.

作为旁注@crossdomain(origin='*') 这似乎很危险,我们不允许跨站点 ajax 请求是有原因的,尽管我相信你有你的理由。

这是我用于测试的完整代码:

from flask import Flask
app = Flask(__name__)

from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper


def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers

            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            if headers is not None:
                h['Access-Control-Allow-Headers'] = headers
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)
    return decorator



@app.route("/", methods=['POST'])
@crossdomain(origin='*')
def hello():
    ss=str(request.form)

    print 'ss: ' + ss + ' request.data: ' + str(request.data)
    return ss


@app.route("/test/")
def t():
    return """
<html><head></head><body>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type='text/javascript'>
jQuery.ajax(
   
      type: "POST",
      dataType: "json",
      data: "adasdasd",
    url: 'http://127.0.0.1:5000/',
complete: function(xhr, statusText)
        alert(xhr.responseText) )

var oReq = new XMLHttpRequest();
oReq.open("POST", "/", false);
oReq.setRequestHeader("Content-Type", "unknown");
oReq.send('sync call');
alert(oReq.responseXML);
</script></body></html>
"""

if __name__ == '__main__':
    app.run()

输出:

$ python test.py 
 * Running on http://127.0.0.1:5000/
127.0.0.1 - - [07/Aug/2012 02:45:28] "GET /test/ HTTP/1.1" 200 -
ss: ImmutableMultiDict([('adasdasd', u'')]) request.data: 
127.0.0.1 - - [07/Aug/2012 02:45:28] "POST / HTTP/1.1" 200 -
ss: ImmutableMultiDict([]) request.data: sync call
127.0.0.1 - - [07/Aug/2012 02:45:28] "POST / HTTP/1.1" 200 -
127.0.0.1 - - [07/Aug/2012 02:45:29] "GET /favicon.ico HTTP/1.1" 404 -

和我的系统:

$ python --version
Python 2.6.1

$ python -c 'import flask; print flask.__version__;'
0.8

$ uname -a
Darwin 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun  7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386

使用谷歌浏览器Version 20.0.1132.57

【讨论】:

【参考方案2】:

我一直在使用类似的功能,在对 ajax 和 python 进行了一些处理之后,这就是我想出的让 python 读取 ajax 数据的方法

JavaScript:

var data = 
      data: JSON.stringify(
                        "value":'asdf'
                    )
   
;

$.ajax(
   url:"/",
   type: 'POST',
   data: data,
   success: function(msg)
              alert(msg);
            
)

Python:

from flask import json
@app.route("/", methods=['POST'])
def get_data():
    data = json.loads(request.form.get('data'))
    ss = data['value']
    return str(ss)

【讨论】:

【参考方案3】:

嗯,我通过request.form 收到 AJAX 请求。我正在使用DataTables 并像这样指定它:

<script type="text/javascript">
$(document).ready( function() 
        $('#mgmtdata').dataTable( 
                "bServerSide": true,
                "sAjaxSource": "url_for('.xhr')|safe",
                "sServerMethod": "POST",
                "bDeferRender": true,  
                "bFilter":  info.filter if info.filter else "false" ,
                "aoColumnDefs": [  info.columndefs|safe if info.columndefs  ],
         );
 );

xhr() 函数很简单:

@usersview.route('/xhr', methods=["POST"])
def xhr():
    if not 'usersview' in g:   
        g.usersview = UsersDatatableView()
    return g.usersview.render()

usersview 是我的 Grid() 对象的一个​​实例。在这种情况下,感兴趣的只是它如何获取 DataTables 发送的 ajax 数据:

def render(self):
    q = self.getQuery()

    # add filtering
    if 'sSearch' in request.form and request.form['sSearch']:
        q = self.applyFilter(q, request.form['sSearch'])

    # add sorting
    if 'iSortingCols' in request.form:
       # and so on

【讨论】:

【参考方案4】:

这对我有用。

在 Javascript 中:

$.ajax(
  type: 'POST',
  url: "enter your correct url",
  contentType: "application/json; charset=utf-8",
  data: JSON.stringify(title: 'My Title', article: 'My article'),
  success: function(result)
    console.log(result)
  
);

在 Python(烧瓶)中:

 from flask import request
 import json

 @app.route("/", methods=['POST'])
 def home():
   json_data = json.loads(request.data)
   print(json_data)
   return json_data

注意:要点是;

JSON.stringify() contentType: "application/json; charset=utf-8" json.loads request.data

【讨论】:

以上是关于Flask没有从jQuery请求数据中获取任何数据的主要内容,如果未能解决你的问题,请参考以下文章

当我尝试从 jquery 将数据传递到 Flask 端点时没有响应

如何从 AJAX 帖子中获取 Flask 中的数据

使用 axios 从 flask-restless API 获取数据

python-flask基础

dataType json 的 jQuery $.ajax 请求不会从 PHP 脚本中检索数据

jQuery 在 ASP.Net MVC 5 中获取请求