通过AJAX发送POST请求时,Console.log显示“ 500(内部服务器错误)”

时间:2019-06-15 21:02:12

标签: mysql ajax api flask

我正在尝试使用Flask创建一个简单的搜索框,当我在框中输入“ m”时,它应该会从AJAX API得到响应,该响应仅显示以“ m”开头的人物姓名,而不会刷新页面。我在SQL工作台中存储了5个以“ m”开头的名称,但是当我在框中输入“ m”时,Chrome浏览器会显示

  

POST http://localhost:5000/users/find 500(内部服务器错误)   jquery.min.js:2

检查网络->响应(预览)都显示

  

NameError:未定义名称“用户名”。

搜索框在“ 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>

我的user.html:     (当我在搜索框中输入“ m”时,这是我要显示所有名称以“ m”开头的页面)

   <div id="all">
      {% for user in users %}
        <p>{{ user.name }}</p>
      {% endfor %}

mySQL表名称为“用户”,列名称为“名称”。我还没有放入JSON,我希望首先通过console.log使其起作用。

您能为我解决上述错误吗?

1 个答案:

答案 0 :(得分:0)

以下内容对于从表单中获取值无效:

starts_with: request.form['starts_with' + "%"]

应该是:

starts_with: request.form['starts_with']

此外,我建议阅读this个问题(和答案),重点突出以这种方式构建查询的安全风险(SQL注入)。

相关问题