Как отправить данные в колбу через форму с вызовом Ajax? - PullRequest
0 голосов
/ 03 ноября 2019

Я создаю приложение Flask, которое я хочу использовать для отображения некоторой очищенной информации. Я импортировал мой файл очистки в Flask, и для его функции очистки я должен передать имя для поиска в качестве параметра. Я хочу получить это имя из поля ввода в моем HTML-коде. Я пытаюсь сделать это, используя вызов Ajax в jQuery, но в настоящее время я получаю ошибку 404.

Я попытался вывести необработанные данные json, а не список python. Я попытался использовать два отдельных вызова Ajax. Я также попытался просмотреть другой пост, на который мне указали, но я столкнулся с этой указанной ошибкой 404.

Код приложения Flask

#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 code

<!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>

Опять же, чтобы быть ясным, моя цель состоит в том, чтобы взять данные из моей формы ввода HTML, нажав один раз на searchBtn, и использовать эти данные в качестве строки в моем параметре для данных webscrape. Затем, когда возвращенные данные возвращаются, я пытаюсь зарегистрировать их на моем console.py

1 Ответ

0 голосов
/ 03 ноября 2019

После перечитывания документации Flask вот мой рабочий код. Однако самое большое изменение, которое мне пришлось сделать, - это загрузить сам файл jQuery и поместить его в мой рабочий каталог в папку с именем «static», чтобы мой index.html мог правильно его загрузить.

Вот мой рабочий код

Код приложения Flask


#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 code

<!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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...