我正在尝试使用 Flask 创建一个简单的搜索框,当我将“m”放入框中时,它应该从 AJAX API 获得响应,仅显示以“m”开头的人名,而不刷新页面。我在 SQL 工作台中存储了 5 个以“m”开头的名称,但是当我将“m”放入框中时,Chrome 检查显示
POST http://localhost:5000/users/find 500 (INTERNAL SERVER ERROR) jquery.min.js:2
检查网络->响应(预览)均显示
NameError: name "username" is not defined.
搜索框在“index.html”中定义。
我尝试将名称更改为“用户名”,但没有成功,而且我不太理解这些错误。
我的 api.py:
@app.route('/')
def index():
return render_template('index.html')
@app.route('/users/find', methods=['POST'])
def find():
mysql = connectToMySQL('usersApi')
query = "SELECT name FROM users WHERE name LIKE %(starts_with)s"
data = {
starts_with: request.form['starts_with' + "%"]
}
users = mysql.query_db(query,data)
print(data)
return render_template('users.html',users=users)
我的index.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='myForm' method= 'POST' action='/users/find'>
<input type="text" id="starts_with" name="starts_with"/>
</form>
<script>
$(document).ready(function(){
$('#starts_with').keyup(function(){
console.log("came here")
$.ajax({
method: 'POST',
url: '/users/find',
data: $('#myForm').serialize(),
success: function(response) {
console.log('received response:', response);
$('#placeholder').html(response)
}
})
})
})
</script>
我的用户.html: (这是我想在搜索框中输入“m”时显示所有以“m”开头的名称的页面)
<div id="all">
{% for user in users %}
<p>{{ user.name }}</p>
{% endfor %}
mySQL 表名是“users”,列名是“name”。我还没有输入 JSON,我希望首先通过 console.log 让它工作。
您能否建议我解决上述错误?
最佳答案
以下内容对于从表单获取值无效:
starts_with: request.form['starts_with' + "%"]
应该是:
starts_with: request.form['starts_with']
此外,我建议阅读 this问题(和答案)强调以这种方式构建查询的安全风险(sql 注入(inject))。
关于mysql - 通过 AJAX 发送 POST 请求时 Console.log 显示 "500 (INTERNAL SERVER ERROR)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56614149/