哈喽大家好,我是鹏哥。
今天继续上周的内容,仍然讲基于Flask开发网站,不过这次的控件是 —— 基于重定向实现搜索功能。
~~~上课铃~~~
1 写在前面
话不多说,在上周的批量删除功能基础上再新增一个搜索功能。因为在实现搜索功能过程中,关于界面重定向问题阻塞了我蛮长一段时间,并且在网上查找资料也无法快速解决我的问题。因此记录下我自己的解决方法,至少也算是一种页面重定向的实现方法。
2 效果展示
3 知识串讲(敲黑板啦)
1、flask重定向的坑:flask.redirect()
一般在百度查找重定向,多数帖子都是用redirect()方法。然后遇到仍然无法跳转的情况,就加上urf_for(),所以我开始的代码是这样的:
@app.route('/search', methods=['get','post'])def search_result():content = request.args.get("search_content")…… # 数据库查询代码省略return redirect(url_for('test.html', content=content, labels=labels))
至少我认为写的没毛病,但是界面死活无法跳转到搜索结果的展示效果。(当然肯定是哪里写的不对,如果有大神知道的话,麻烦告知下)
2、通过window.location.href实现重定向
这里实现界面跳转的方式就不一样了,之前是通过Flask框架中的redirect方法,这里是在html的javascript方法中直接跳转到新界面,连获取request.args.get("search_content")的步骤都省略了。
<!--新增搜索功能--><script>(function(){$('input[id="search"]').on('click', function(){var content = document.getElementById("search_content").value;var data = {"search_content":content};$.ajax({type: "get",url: "/",data: data,dataType: "json",success:window.location.href="search_result/"+content});});})();</script>
这是搜索功能的html代码,与之前方法的不同之处在于最后一句:success:window.location.href="search_result/"+content,即在点击搜索按钮后直接跳转网页到http://xx.xx.xx.xx/search_result/content。
然后对应的在flask框架中进行新界面的实现。
4 示例代码
<td><input type="text" placeholder="请输入设备IP" id="search_content"><input type="button" value="开始搜索" id="search"></td>
@app.route('/search_result/<content>', methods=['get','post'])def search_result(content):sql = "select * from material_table where 网络IP='{}'".format(content)cur = con.cursor()cur.execute(sql)content = cur.fetchall()labels = [tuple[0] for tuple in cur.description]return render_template('test.html', content=content, labels=labels)
5 总结
~~~下课铃~~~
【往期热门文章】:
【Python成长之路】10行代码教你免费观看无广告版的《庆余年》腾讯视频
【关注“鹏哥贼优秀”公众号,回复“python学习材料”,将会有python基础学习、机器学习、数据挖掘、高级编程教程等100G视频资料,及100+份python相关电子书免费赠送!】
扫描二维码
与鹏哥一起
学python吧!