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

标签 jquery python flask

我有一个 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) }})

没有返回

最佳答案

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

Incoming Request Data

data
  Contains the incoming request data as string in case it came with a mimetype Flask does not handle.

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

但是由于我们正在使用 json flask 执行标准的 POST 可以很好地处理这个问题,因此您可以从标准的 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

使用谷歌浏览器 版本 20.0.1132.57

关于jquery - Flask 没有从 jQuery 请求数据中获取任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11839855/

相关文章:

c# - MVC 5 + $Post() 函数在服务器上托管后无法正常工作

python - 将发布数据传递到脚本 flask

javascript - 在 HTML 中使用 Canvas 时不显示文本

jquery - 将动态CSS添加到同一类的不同实例

python - 将 .CSV 转换为 .DBF(dBASEIII) VFP 6.0,一切都变成了备忘录字段

python - 使selenium单击具有相同类别的连续元素n次

python - Jinja2圆形过滤器不四舍五入

flask - Minikube上的Ingress Controller无法正确路由Flask POST请求

javascript - 模式打开时锁定背景

Python 解释器和脚本输出不同的结果