Python 如何通过带有Ajax调用的表单向flask提交数据?
我正在创建一个烧瓶应用程序,我想用它来显示一些粗略的信息。我已经将我的刮片文件导入到Flask中,对于它的刮片功能,我必须传递一个名称作为参数进行搜索。我想从HTML代码中的输入框中获取此名称。我试图在jQuery中使用Ajax调用来实现这一点,但目前我遇到了404错误 我尝试输出原始json数据,而不是python列表。我尝试过使用两个单独的Ajax调用。我也试着看了另一篇文章,我被指在这里,但我遇到了这个404错误 烧瓶应用程序代码Python 如何通过带有Ajax调用的表单向flask提交数据?,python,jquery,json,ajax,flask,Python,Jquery,Json,Ajax,Flask,我正在创建一个烧瓶应用程序,我想用它来显示一些粗略的信息。我已经将我的刮片文件导入到Flask中,对于它的刮片功能,我必须传递一个名称作为参数进行搜索。我想从HTML代码中的输入框中获取此名称。我试图在jQuery中使用Ajax调用来实现这一点,但目前我遇到了404错误 我尝试输出原始json数据,而不是python列表。我尝试过使用两个单独的Ajax调用。我也试着看了另一篇文章,我被指在这里,但我遇到了这个404错误 烧瓶应用程序代码 #Start the flask app app = Fl
#Start the flask app
app = Flask(__name__)
#Start page
@app.route('/')
def index():
return render_template('index.html')
#What happens when our button is clicked
@app.route('/_get_data')
def _get_data():
#Get the name we want to search for
searchName = request.args.get('searchName')
#Call the function and pass our search name parameter
dataList = scrape_data(searchName)
#Return the json format of the data we scraped
return jsonify(dataList = dataList)
#Run the app
if __name__ == "__main__":
app.run(debug = True)
index.html代码
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>NBA Data Web App</title>
</head>
<body>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin = "anonymous"></script>
<script type = text/javascript src = "{{url_for('static', filename = 'jquery.js') }}"></script>
<form id = "nameForm" role = "form">
<input name = "text">
<button id = "searchBtn"> Search </button>
</form>
<div id = "container"></div>
<script type = text/javascript> $SCRIPT_ROOT = {{ request.script_root|tojson|safe }}; //Get the root of our data </script>
<script type = "text/javascript">
//Root so we can get the data from our form
$('button#searchBtn').click(function(e) {
//Prevent our form from submitting
e.preventDefault();
//Get the root
$.getJSON($SCRIPT_ROOT + '/_get_data', {
//Our searchName variable will be the one from our HTML input box
searchName: $('input[name = "text"]').val(),
}, function(data) {
console.log(data.dataList);
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>NBA Data Web App</title>
</head>
<body>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin = "anonymous"></script>
<script type = text/javascript src = "{{
url_for('static', filename = 'jquery.js') }}"></script>
<form id = "nameForm" role = "form">
<input name = "text">
<button id = "searchBtn"> Search </button>
</form>
<div id = "container"></div>
<script type = text/javascript>
//Root stuff
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
//Root so we can get the data from our form
$('button#searchBtn').click(function(e) {
//Prevent our form from submitting, which is its default action/purpose
e.preventDefault();
//Get the data from our function in the Flask App
$.getJSON($SCRIPT_ROOT + '/_get_data', {
//Our searchName variable will be the one from our HTML input box
searchName: $('input[name = "text"]').val(),
}, function(data) {
//Rename the variable so I can reuse some code
data_list = data.dataList;
//HTML table variables
var perRow = 1, count = 0, table = document.createElement("table"),
row = table.insertRow();
//Loop through the data and get each piece
for (var i of data_list) {
//Create a cell for each piece of data
var cell = row.insertCell();
//Then actually add the data to the cell
cell.innerHTML = i;
//Increment our count variable so we can decide when to start a new row
count++;
if (count % perRow == 0) {
//If we have reached our set limit of items per row, start a new row
row = table.insertRow();
}
}
//Attach the table to the HTML doc when finished
document.getElementById("container").appendChild(table);
});
});
</script>
</body>
</html>
NBA数据网络应用程序
搜寻
$SCRIPT_ROOT={{request.SCRIPT_ROOT|tojson|safe}//获取数据的根
//Root,这样我们就可以从表单中获取数据
$(“按钮#搜索BTN”)。单击(函数(e){
//阻止我们的表单提交
e、 预防默认值();
//扎根
$.getJSON($SCRIPT\u ROOT+'/\u get\u data'{
//我们的searchName变量将是HTML输入框中的变量
searchName:$('input[name=“text”]).val(),
},函数(数据){
console.log(data.dataList);
});
});
同样,我的目标是通过单击
searchBtn
,从HTML输入表单中获取一次数据,并将该数据作为参数中的字符串用于webscrape数据。然后,一旦刮取的数据返回,我将尝试将其记录到我的控制台。py在重新阅读一些Flask文档后,下面是我的工作代码。然而,我必须做的最大改变是下载jQuery文件本身,并将其放在名为“static”的文件夹中的工作目录中,以便我的index.html可以正确加载它
这是我的工作代码
烧瓶应用程序代码
#Import our external web scraping file
from scrape import *
#Flask dependencies
from flask import Flask, render_template, jsonify, request, escape, url_for
#Get our lists to post
headers = data_headers()
#Start the flask app
app = Flask(__name__)
#Start page
@app.route('/')
def index():
return render_template('index.html')
#What happens when our button is clicked
@app.route('/_get_data')
def _get_data():
#Get the name we want to search for
searchName = request.args.get('searchName')
#Call the function and pass our search name parameter
dataList = scrape_data(searchName)
#Return the json format of the data we scraped
return jsonify(dataList = dataList)
#Run the app
if __name__ == "__main__":
app.run(debug = True)
index.html代码
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>NBA Data Web App</title>
</head>
<body>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin = "anonymous"></script>
<script type = text/javascript src = "{{url_for('static', filename = 'jquery.js') }}"></script>
<form id = "nameForm" role = "form">
<input name = "text">
<button id = "searchBtn"> Search </button>
</form>
<div id = "container"></div>
<script type = text/javascript> $SCRIPT_ROOT = {{ request.script_root|tojson|safe }}; //Get the root of our data </script>
<script type = "text/javascript">
//Root so we can get the data from our form
$('button#searchBtn').click(function(e) {
//Prevent our form from submitting
e.preventDefault();
//Get the root
$.getJSON($SCRIPT_ROOT + '/_get_data', {
//Our searchName variable will be the one from our HTML input box
searchName: $('input[name = "text"]').val(),
}, function(data) {
console.log(data.dataList);
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>NBA Data Web App</title>
</head>
<body>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin = "anonymous"></script>
<script type = text/javascript src = "{{
url_for('static', filename = 'jquery.js') }}"></script>
<form id = "nameForm" role = "form">
<input name = "text">
<button id = "searchBtn"> Search </button>
</form>
<div id = "container"></div>
<script type = text/javascript>
//Root stuff
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
//Root so we can get the data from our form
$('button#searchBtn').click(function(e) {
//Prevent our form from submitting, which is its default action/purpose
e.preventDefault();
//Get the data from our function in the Flask App
$.getJSON($SCRIPT_ROOT + '/_get_data', {
//Our searchName variable will be the one from our HTML input box
searchName: $('input[name = "text"]').val(),
}, function(data) {
//Rename the variable so I can reuse some code
data_list = data.dataList;
//HTML table variables
var perRow = 1, count = 0, table = document.createElement("table"),
row = table.insertRow();
//Loop through the data and get each piece
for (var i of data_list) {
//Create a cell for each piece of data
var cell = row.insertCell();
//Then actually add the data to the cell
cell.innerHTML = i;
//Increment our count variable so we can decide when to start a new row
count++;
if (count % perRow == 0) {
//If we have reached our set limit of items per row, start a new row
row = table.insertRow();
}
}
//Attach the table to the HTML doc when finished
document.getElementById("container").appendChild(table);
});
});
</script>
</body>
</html>
NBA数据网络应用程序
搜寻
//根茎
$SCRIPT_ROOT={{request.SCRIPT_ROOT|tojson|safe};
//Root,这样我们就可以从表单中获取数据
$(“按钮#搜索BTN”)。单击(函数(e){
//阻止表单提交,这是表单的默认操作/目的
e、 预防默认值();
//从Flask应用程序中的函数获取数据
$.getJSON($SCRIPT\u ROOT+'/\u get\u data'{
//我们的searchName变量将是HTML输入框中的变量
searchName:$('input[name=“text”]).val(),
},函数(数据){
//重命名变量,以便可以重用一些代码
data_list=data.dataList;
//HTML表变量
var perRow=1,count=0,table=document.createElement(“table”),
行=table.insertRow();
//循环浏览数据并获得每个片段
用于(数据列表的变量i){
//为每段数据创建一个单元格
var cell=row.insertCell();
//然后实际将数据添加到单元格中
cell.innerHTML=i;
//增加count变量,以便决定何时开始新行
计数++;
如果(计数%perRow==0){
//如果我们已达到每行项目的设置限制,请开始新的一行
行=table.insertRow();
}
}
//完成后将表格附加到HTML文档
document.getElementById(“容器”).appendChild(表);
});
});
对于初学者,您需要防止按钮单击的默认操作,该操作将提交表单并重新加载页面。好,现在需要更多关于什么有效和什么无效的调试细节。404显然是一个路径问题,所以对于初学者来说,$SCRIPT\u ROOT+'/\u get\u data'
是否提供了有效的路径?这里确实没有足够的了解,需要隔离它是前端还是后端issue@charlietfl最简单的测试方法是什么?console.log($SCRIPT\u ROOT+'/\u get\u data')
。。。然后应该能够使用一个示例查询字符串将其放入地址栏,并查看一些json输出。更高级的方法是在浏览器开发工具网络中检查实际请求,并复制从中生成的urlthere@charlietfl我只是那样做了。我的问题是,我在跟踪另一个StackOverflow帖子来创建这个,所以没有“静态”
。但是,我不确定我需要顶部框中的url做什么。也许是我的索引页?