2016-11-14 158 views
0

我在开发基于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) 
+0

我对python没有太多的了解,但是这个代码究竟是什么“错误”?正如你目前得到的输出是什么?我相信,首先,你必须因此,数据:{value1:“value”,value2:2}等 – ccopland

+0

当我运行这个,我得到这个错误:jquery-1.11.2.js:9659 POST http ://127.0.0.1:5005/wordQuery 400(BAD REQUEST) –

+0

是你的url正确的参数吗?我不认为是这样。服务器ajax请求的完整url是什么? –

回答

0

我在您的HTML中看不到form元素。你可能是POST ing空数据

+0

我在''div id =“custom-search-input”>上面添加了'form'元素,但是在查询时我得到相同的错误:jquery-1.11.2.js:9659 POST 127.0.0.1:5005/ wordQuery 400(BAD REQUEST) –

相关问题