python获取表单数据,这是怎么回事? [英] python get form data how can this be?

查看:343
本文介绍了python获取表单数据,这是怎么回事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的js函数为ajax表单提交:
$ b $ pre $('。sendButton')。on('click' ,函数(){
$ .post(/ send-form,$('#contactForm')。serialize())
}



这是我的形式:

pre $ < form id = contactForm>
< input id =fastNamename =nametype =text/>
< input id =fastPhonename =phonetype =文本/>
< div class =sendButton> send< / div>
< / form>
< / code> >

这是我的后端函数来处理它,我正在使用python,flask

  @ app.route(/ send-form,methods = ['POST'])
def send_form():
data = request.data
print request.data

在我的控制台中输出数据:

 127.0.0.1  -  [22 / Feb / 2015 23:50:54]POST / send-form HTTP / 1.1200  -  name = dfdsf& phone = 89920203725 

但是我在另一个项目中做了同样的事情,它什么都不打印。
详情在这里:
无法获得后ajax请求数据python
这怎么可能?

解决方案

数据在request.form字段中,可以通过以下方式获取:

  name = request.form ['name'] 
phone = request.form ['phone']

备注。如果他们没有被发送,这段代码将抛出一个异常。



更长的解释
原因是数据发送使用名为 application / x-www-form-urlencoded 的编码。这些数据位于request.data字段中,但为了解码,您可以使用request.form,Flask会自动将其解码为application / x-www-窗体-urlencoded 。

This is my js function for ajax form submit:

$('.sendButton').on('click', function(){
    $.post( "/send-form", $('#contactForm').serialize())
}

This is my form:

<form id="contactForm">
    <input id="fastName" name="name" type="text" />
    <input id="fastPhone" name="phone" type="text" />
    <div class="sendButton">send</div>
</form>

And this is my backend function to handle it, I am using python, flask

@app.route("/send-form", methods=['POST'])
def send_form():
    data = request.data   
    print request.data

And in my console it prints data:

127.0.0.1 - - [22/Feb/2015 23:50:54] "POST /send-form HTTP/1.1" 200 - name=dfdsf&phone=89920203725

But I did the same in another project and it prints nothing. Details are here: Can't get post ajax request data python How can this be possible?

解决方案

The data is in the field request.form, and can be fetched by:

name = request.form['name']
phone = request.form['phone']

Remark. If they are not sent with, this code will throw an exception.

Longer explanation The reason is that the data is sent using a encoding known as application/x-www-form-urlencoded. The data is in request.data field, but to decode it you can use request.form, and Flask will automatically decode it as application/x-www-form-urlencoded.

这篇关于python获取表单数据,这是怎么回事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆