从 html 中获取数据并<对其进行一些操作>并使用ajax或js将数据传回前端 [英] Get data from html and <do some operation on it> and pass the data back to the front end using ajax or js

查看:19
本文介绍了从 html 中获取数据并<对其进行一些操作>并使用ajax或js将数据传回前端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

到目前为止我做了什么:

有一个用户表单,用户可以在其中输入详细信息并点击提交,然后他会得到一个 json 输出.

在这种形式中,我有一个搜索按钮,当用户输入一个字符串时,该字符串被发送到烧瓶应用程序路由,并且很少进行搜索操作并输出一个项目列表(直到这部分工作!)

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

这是我目前所做的:

 var successFunction = function(response) {/* 在这里做点什么 */$('#info').html(JSON.stringify(data, null, ' '));});}$(函数(){$('#btnSignUp').click(function(){$.ajax({网址:'/注册',数据:$('form').serialize(),类型:'POST',成功:成功函数(响应)错误:函数(错误){控制台日志(错误);}});});});

flask 应用程序有这样的东西:

from flask import Flask, render_template, request,jsonify,url_for导入 json,os,reapp = Flask(__name__)@app.route('/',methods=['GET','POST'])定义形式():if request.method == 'POST': #这个块只有在表单提交时才进入结果 = { key: value[0] if len(value) == 1 else value对于 key,request.form.iterlists() 中的值}返回 json.dumps(result,indent=2)return render_template('form_backup1.html')@app.route("/signUp", methods=["POST","GET"])定义注册():jsdata = request.form['硝基']<几个查找和搜索操作,其输出在这个下拉列表列表>返回 jsonify(dropdown_list)如果 __name__ == '__main__':app.run(host="0.0.0.0",port="5000",debug = True)

截取 html 页面只是为了显示搜索框:

 

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">搜索</button><pre id="信息"></pre>

正如我所说,当用户单击搜索时,我能够获取用户在 html 表单中输入的文本.python 的输出列表是我无法进入前端的地方.

对此的任何帮助将不胜感激.

谢谢

解决方案

您可以在 Jquery 中使用 ajax.您可以查看此文档了解更多详情.

如何进行:

  1. 配置js脚本

在您的 HTML 文件模板中:

  • 加载 Jquery:

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

要么是静态的:

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

或者使用 Google 的 AJAX 库 API:

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

  • 添加网站的动态路径:

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

    1. 在 Flask 一侧

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

@app.route("/_signUp")定义注册():myString = request.args.get('myString')"""几个查找和搜索操作,其输出在这个下拉列表列表"""dropdown_list = ['A', 'B', 'C'] #sample返回 jsonify(dropdown_list=dropdown_list)

  1. 返回 HTML 代码

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

<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">搜索</button><pre id="信息"></pre>

有关详细信息,请参阅此链接.

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:

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

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)

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>

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.

Thanks

解决方案

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

How to proceed:

  1. Configure js scripts

In your HTML file template:

  • Load Jquery:

Load Jquery preferably before any other javascript files.

Either statically:

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

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>

  • Add a dynamic path to the site:

    <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. On the side of Flask

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. Back in the HTML code

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>

See this link for more details.

这篇关于从 html 中获取数据并&lt;对其进行一些操作&gt;并使用ajax或js将数据传回前端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆