我在開發基於flask-python的應用程序時更新,並陷入了一些困境。問題是我無法從mysql中檢索數據。如何使用JSON,JQuery和AJAX從服務器獲取數據?
首先,讓我分享一些文件的內容,至少是其中的一部分內容。對於html,我使用bootstrap。
的index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="../static/css/search-bar.css">
<script type=text/javascript src="{{ url_for('static', filename='js/jquery-1.11.2.js') }}"></script>
<script type=text/javascript src="{{ url_for('static', filename='js/wordQuery.js') }}"></script>
</head>
<body>
<div class="jumbotron">
<h1>Search</h1>
<div class="container">
<div class="row">
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" id="wordInput" class="form-control input-lg" placeholder="Please type the word you want to search" />
<span class="input-group-btn">
<button class="btn btn-info btn-lg" type="button" id="btnWordSearch">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
app.py:
from flask import Flask, render_template, json, jsonify, request
from flaskext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash
mysql = MySQL()
app = Flask(__name__)
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'USER_NAME'
app.config['MYSQL_DATABASE_PASSWORD'] = 'PASSWORD'
app.config['MYSQL_DATABASE_DB'] = 'DATABASE_NAME'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
@app.route('/')
def main():
return render_template('index.html')
@app.route('/wordQuery', methods=['POST', 'GET'])
def checkWord():
word = request.form['wordInput']
success = "OK"
error = "NOK"
word = word.lower()
try:
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `word` FROM `allwords` \
WHERE `word` like %s"
cursor.execute(sql, (word + "%",))
result = cursor.fetchone()
if result is not None:
return json.dumps({'message': 'The word exists in the database !'})
else:
return json.dumps({'error': str(data[0])})
except Exception as e:
return json.dumps({'error': str(e)})
finally:
cursor.close()
conn.close()
if __name__ == "__main__":
app.run(debug=True, port=5005)
wordQuery.js:
$(function(){
$('#btnWordSearch').click(function(){
$.ajax({
url: '/wordQuery',
data: $('form').serialize(),
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
});
我希望看到的是,當WO rd被搜索,它應該在數據庫中找到並且瀏覽器控制檯應該寫入消息'The word exists in the database!'。後來,我想實現另一個給出結果的html頁面。
非常感謝您的幫助!
UPDATE:
我提示以下錯誤:當我第一次張貼了這個問題就在這裏;
jquery-1.11.2.js:9659 POST 127.0.0.1:5005/wordQuery 400 (BAD REQUEST)
但是,現在我改變了我的html文件中的一部分。有這樣一個id
元素:id="wordInput"
我改變它是這樣的:name="wordInput"
。在這個變化之後,我得到了如下的新錯誤;
jquery-1.11.2.js:9659 POST http://127.0.0.1:5005/wordQuery 500 (INTERNAL SERVER ERROR)
我對python沒有太多的瞭解,但是這個代碼究竟是什麼「錯誤」?正如你目前得到的輸出是什麼?我相信,首先,你必須因此,數據:{value1:「value」,value2:2}等 – ccopland
當我運行這個,我得到這個錯誤:jquery-1.11.2.js:9659 POST http ://127.0.0.1:5005/wordQuery 400(BAD REQUEST) –
是你的url正確的參數嗎?我不認爲是這樣。服務器ajax請求的完整url是什麼? –