Python Flask接收Ajax POST与GET数据的实现方法

小鹿同学
小鹿同学
发布时间:2026-10-14 | 6人浏览过
原创

本文详细解析Python Flask框架如何接收前端Ajax发送的POST和GET数据。通过对比request.form.get与request.values.get两种方法,展示不同提交方式在后端的处理差异,并提供完整的Ajax请求、HTML表单及Flask路由代码示例,帮助开发者实现高效的数据交互。

前端通过Ajax向后端发送数据请求。

一、POST方式提交

具体Ajax配置如下:


@app.route("/find_worldByName",methods=['POST'])
type:'post',
data:{'cname':cname,'continent':continent},
这是post方式传值
那么在后台接收就是:(使用request的form方法)
continent = request.form.get("continent")
cname = request.form.get("cname")

二、GET方式(URL参数)提交

后端使用request对象的values方法进行处理。


使用request的values方法

data:{'cname':cname,'continent':continent},
name=request.values.get("cname")

三、总结对比

这两种方式的核心区别在于Ajax data中数据的发送机制不同(即GET与POST的区别),因此后端接收数据的逻辑也有所不同。使用request.form.get方法获取的是一个JSON字符串(该方法会自动解析JSON对象,允许直接通过key访问属性);而使用request.values.get方法获取的是通过URL传递的GET参数。

以下是整个流程的实现代码:Ajax部分如下:


//查询js
function find_res(){
    var cname;
    var continent;
    // $.ajax
    // ({
    //     method:"post",
    //     url:"http://localhost:8080/PycharmProjects/Cov/templates/world.html?_ijt=q6ulfhihrfp8rqkl8id73svio3",
    //     success:function(data)
    //     {
    //         //form表单数据的转化,转化成[ { name: , value:   },{ name: , value:   } ]
    //         all=$('#find_value').serializeArray()
    //         // console.log(all['cname'])
    //         console.log(all[0])
    //         cname=all[0]['value']
    //         alert(cname)
    //     }
    // })
    cname=document.getElementById("cname").value
    continent=document.getElementById("continent").value
    console.log(cname+continent)
    // alert("表单数据:   "+"国家:"+cname+ "大洲:"+ continent)
    $.ajax
    ({
            // sync:true,
            url:"/find_worldByName",
            // type:'post',
            data:{'cname':cname,'continent':continent},
            success:function (data)
            {
                // alert("!!!")
                table_data=data.data;
                for(var i=0;i<table_data.length;i++)
                {
                // console.log(table_data[i]);
                }
            var appendHTML = "";
        if($(".map-table tbody tr").length>0){
            $(".map-table tbody tr").remove();
        }
        // alert("list长度:"+table_data.length)
        for(var i=0; i<table_data.length; i++)
            {
            //分割日期字符串
            strdt=table_data[i][1].split(" ");
            strdt=strdt[0]+strdt[1]+strdt[2]+strdt[3]
            appendHTML = "<tr align='center' style='color:aquamarine;'><td>"+
            strdt+"</td><td>"+
            table_data[i][2]+"</td><td>"+
            table_data[i][5]+"</td><td>"+
            table_data[i][8]+"</td><td>"+
            table_data[i][9]+"</td><td>"+
            table_data[i][4]+"</td><td>"+
            (i+1)+"</td></tr>";
                $(".map-table tbody").append(appendHTML);
            }
        }
    })
}

前端HTML结构如下:


<table align="center" style="margin:3px"  cellspacing="7px">
                <form id="find_value">
                    <label><font color="#ff7f50">输入国家:</font></label>
                    <input id="cname" type="text" name="cname" placeholder="" value="">

                    <label><font color="#ff7f50">输入大洲:</font></label>
                    <input id="continent" type="text" name="continent" placeholder="" value="">

                    <input type="button" value="查询" onclick="find_res()">
                    <input type="reset" value="重置">
                </form>
                <thead>
                 <tr style="color: #FFB6C1">
                <th>时间</th>
                <th>国家</th>
                <th>累计确诊</th>
                <th>累计治愈</th>
                <th>累计死亡</th>
                <th>现存确诊</th>
                <th>排名</th>
              </tr>
                </thead>
                <tbody id="bd_data">
                </tbody>
            </table>

Python Flask路由定义如下:


@app.route("/find_worldByName")
def find_worldByName():
    #获取用户传来的数据
    # jsondata = json.loads(request.form.get('jsondata'))
    res=[]
    #get方式
    cname = request.values.get("cname")
    continent = request.values.get("continent")
    #post方式
    # continent = request.form.get("continent")
    # cname = request.form.get("cname")

    # print(cname+continent)
    res=utils.find_worldByName(cname,continent)
    # res = utils.find_worldByName("美国", "")
    # print(res)
    return jsonify({"data": res})

后端从数据库获取数据的逻辑如下:


def find_worldByName(c_name,continent):
    print(c_name)
    print(continent)
    sql = " SELECT * FROM world WHERE  1=1 "
    if(c_name!=None):
        sql=sql+"AND ( c_name LIKE '%"+c_name+"%' )"
    if(continent!=None):
        sql=sql+" AND ( continent LIKE '%"+continent+"%') "
    sql=sql+" AND dt=(SELECT dt FROM world order by dt desc limit 1) order by confirm desc "

          # "AND continent LIKE '%%%%%s%%%%'" \
          # " order by dt desc " %(c_name,continent)
    # sql_temp = " SELECT * FROM world WHERE c_name LIKE '%"+c_name+"%' "
    res = query(sql)
    list= []
    for i in res:
        # print(i)
        list.append(i)
    return list;
def query(sql,*args):
    """
    通用封装查询
    :param sql:
    :param args:
    :return:返回查询结果 ((),())
    """
    conn , cursor= get_conn()
    print(sql)
    cursor.execute(sql)
    res = cursor.fetchall()
    close_conn(conn , cursor)
    return res

至此,关于Python Flask接收前台Ajax POST和GET数据的方法介绍完毕。如需了解更多相关Python Flask接收前台Ajax POST和GET数据的内容,请搜索本站历史文章或继续浏览后续文章。感谢大家的支持!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表