1

Пишу небольшое веб приложение на Python Flask. Необходимо, чтобы оно работало в локальной сети. Когда я открываю http://127.0.0.1:49555/, используется файл index.html. Как сделать так, чтобы после выполнения функции CreateGameBtnF() у меня начал использоваться файл leader.html? Заранее спасибо

PS функция CreateGameBtnF() вызывается после нажатия на кнопку.

Вот Python код:

from flask import Flask, render_template, request, jsonify, redirect
import json
    
app =  Flask(__name__)

@app.route('/creategame', methods=['POST'])
def creategame():
    print(request.environ.get('HTTP_X_REAL_IP', request.remote_addr))
    return redirect(render_template('leader.html'))

@app.route('/connect', methods=['POST'])
def connect():
    print('asdasdsad')
    return 'Подключено'

@app.route('/')
def index():
    return render_template('index.html')
 
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=49555, debug=True)

Вот JS код:

function CreateGameBtnF() {
    let response = fetch("/creategame", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            e: 's'
        }),
    });
}

function ConnectBtnF() {
    let response = fetch("/connect", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            name: 's'
        }),
    });
}
2
  • я правильно понимаю, что вы хотите контентом из leader.html заменить текущий контент страницы?
    – alex
    6 сен 2020 в 12:32
  • @alex, да, именно это, извините что так долго 6 сен 2020 в 13:40

1 ответ 1

2
# ajax
<script>
        $(function() {
          $('form').submit(function(e) {
            var $form = $(this);
            $.ajax({
              type: $form.attr('method'),
              url: $form.attr('action'),
              data: $form.serialize()
          }).done(function(response) {
            var json = jQuery.parseJSON(response)
            $('#data').html(json.data);
            console.log('success');
        }).fail(function() {
          console.log('fail');
      });
        e.preventDefault(); 
    });
      });
</script>

# форма запроса данных
<form action="/get_data" method="post" id="finduser" name="form">
...
<button type="submit" name="finduser" value="Validate">Поиск</button>

# отображение данных с помощью ajax
<section>
<div class="container">
    <div class="d-flex bd-highlight">
        <div id="data"></div>
    </div>
</div>
# обработка данных и возврат на страницу
@app.route('/get_data', methods=['POST'])
def get_data():
    lst = search_user(request.form['name'].lower())
    return json.dumps({'data': render_template('response.html', lst=lst, len=range(0, len(lst)))})

# response.html
{% block content %}
<div class="container">
    {% if lst == 'empty' %}
    {% else %}
    <div class="row">
        {% for i in len %}
        <div class="col-sm-4">
            <div class="card" style="width: 20rem; height: 20,5rem; margin-bottom: 10px;">
                <div class="card-header">
                    <strong>{{lst[i]['l_name']}} {{lst[i]['f_name']}} {{lst[i]['middle']}}</strong>
            </div>
        </div>
        {% endfor %}
    </div>
    {% endif %}
</div>
{% endblock %}

черпал отсюда

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.