从html获取数据并<对其执行某些操作>并使用ajax或js将数据传回前端

从html获取数据并<对其执行某些操作>并使用ajax或js将数据传回前端

问题描述:

我正在尝试从网页上获取数据到我的烧瓶应用程序,并在对其进行一些操作后,输出列表我试图将其作为下拉列表发送回前端。

I am trying to get data from webpage to my flask app and after a few operations on it,the output list im trying to send it back to front end as a dropdown list.

到目前为止我做了什么:

What i have done till now:

有一个用户表单,用户输入详细信息并点击提交,他获得了json输出。

there is a user form where the user enters details and clicks on submit and he gets a json output.

在这种形式下,我有一个搜索按钮,当用户输入一个字符串时,该字符串被发送到烧瓶应用程序路径并完成很少的搜索操作并输出一个列表items(TILL这部分它正在工作!)

in this form,I have a search button which when the user inputs a string,that string is sent to the flask app route and few search operations are done and outputs a list of items(TILL this part it is working!)

我需要开始工作的是输出列表应该再次发送回我无法获取的表单页面它是工作。

What i need to get to work is the output list should again be sent back to the form page which i have trouble getting it to work.

这是我到目前为止所做的:

This is what i have done so far:

    var successFunction = function(response) {
     /* do something here */
            $('#info').html(JSON.stringify(data, null, '   '));
    });
}
$(function(){
        $('#btnSignUp').click(function(){

                $.ajax({
                        url: '/signUp',
                        data: $('form').serialize(),
                        type: 'POST',
                        success: successfunction(response)
                        error: function(error){
                                console.log(error);
                        }
                });
        });
});

烧瓶应用程序具有以下内容:

the flask app has something like this:

from flask import Flask, render_template, request,jsonify,url_for
import json,os,re
app = Flask(__name__)

@app.route('/',methods=['GET','POST'])
def form():
        if request.method == 'POST': #this block is only entered when the form is submitted
                result = { key: value[0] if len(value) == 1 else value
                      for key, value in request.form.iterlists()
                        }
                return json.dumps(result,indent=2)
        return render_template('form_backup1.html')


@app.route("/signUp", methods=["POST","GET"])
def signUp():
        jsdata = request.form['Nitro']
        <couple of find and search operations the output of which is in 
        this dropdown_list list>
        return jsonify(dropdown_list)

if __name__ == '__main__':
   app.run(host="0.0.0.0",port="5000",debug = True)

剪切html页面只是为了显示搜索框:

snipped html page just to show the search box:

      <div id='nitroo'>
      Nitro_search: <input type="text" placeholder="Apply Nitro" name="Nitro" id="Nitro">
      <button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button">Search</button>
       <pre id="info"></pre>

正如我所说,当我点击时,我能够获得用户在html表单中输入的文字在搜索上。
来自python的输出列表是我无法前往前端的地方。

As I said I am able to get the text entered by the user in the html form when he clicks on search. the output lists from python is where I am having trouble of getting to front end.

对此的任何帮助都将非常感激。

Any help on this would be much appreciated.

谢谢

您可以将ajax与Jquery一起使用。您可以查看此文档了解更多详情。

You can use ajax with Jquery. You can see this doc for more details.

如何继续:


  1. 配置js脚本

  1. Configure js scripts

在您的HTML文件模板中:

In your HTML file template:


  • 加载Jquery

  • Load Jquery:

最好在任何其他javascript文件之前加载Jquery。

静态地:

<script type=text/javascript src="{{url_for('static', filename='jquery.js') }}"> </script>

或使用Google的AJAX Libraries API:

Or using Google’s AJAX Libraries API:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="{{url_for('static', filename='jquery.js') }}">\x3C/script>')</script>




  • 添加网站的动态路径

    <script type=text/javascript>$SCRIPT_ROOT = {{ request.script_root|tojson|safe }}; </script>
    

    此脚本标记将全局变量设置为应用程序根目录的前缀。

    This script tag sets a global variable to the prefix to the root of the application.


    1. 在Flask一侧

    1. On the side of Flask


  • 编写一个函数,该函数将用户在表单中输入的值作为参数,执行搜索操作并返回带有列表的JSON对象希望显示。

    Write a function that will take as argument the value entered in the form by the user, perform search operations and return a JSON object with the list you want to display.

@app.route("/_signUp")
def signUp():
    myString = request.args.get('myString')

    """couple of find and search operations the output of which is in 
    this dropdown_list list"""

    dropdown_list = ['A', 'B', 'C'] #sample

    return jsonify(dropdown_list=dropdown_list)




  1. 返回HTML代码

  1. Back in the HTML code

编写一个脚本,检索输入的数据,将它们以Ajax形式发送到服务器并显示服务器返回的信息。

Write a script that will retrieve the data entered, send them in Ajax to the server and display the information returned by the server.

<script type=text/javascript>
    $(function(){
        $('#btnSignUp').bind('click', function(){
            $.getJSON($SCRIPT_ROOT + '/_signUp', {
                myString: $('input[name="Nitro"]').val(),
            },function(data){
                $('#info').append('<li>' + data.dropdown_list[0] + '</li>' );//A
                $('#info').append('<li>' + data.dropdown_list[1] + '</li>' );//B
                $('#info').append('<li>' + data.dropdown_list[2] + '</li>' );//C
            }
        });
    });
</script>
<div id='nitroo'>
    Nitro_search: <input type="text" placeholder="Apply Nitro" name="Nitro" id="Nitro">
    <button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button">Search</button>
   <pre id="info"></pre>
</div>

参见此链接了解更多详情。