您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:Python的flask接收前台的ajax的post数据和get数据的方法

51自学网 2021-10-30 22:45:57
  python
这篇教程Python的flask接收前台的ajax的post数据和get数据的方法写得很实用,希望能帮到您。

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:

//查询jsfunction 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数据内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net!


Python使用sql语句对mysql数据库多条件模糊查询的思路详解
python glom模块的使用简介
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。