简体   繁体   English

如何将数据从 Flask 发送到 JavaScript?

[英]How I can send data from Flask to JavaScript?

Hello I am new and building an application in Flask and Javascript.您好,我是新手,正在 Flask 和 Javascript 中构建应用程序。 I have a problem with sending data from Flask do JavaScript.我从 Flask 和 JavaScript 发送数据时遇到问题。

I have code in routes.py我在 routes.py 中有代码

@app.route('/mapaa',methods=['GET','POST'])
def mapa():
    user_id = current_user.get_id()
    slownik = {}


    if 'event_form' in request.form:
        name = request.form['name_event']
        all_data = Event.query.filter_by(name=name).all()
        for row in all_data:
            date_st_string = str(row.date_start)
            date_end_string = str(row.date_end)
            slownik = {'id':row.id,'date_st':date_st_string,'date_end':date_end_string,'type':row.type,'name':row.name,'len_route':row.len_route,'route':row.route}
        return jsonify(slownik)
    return render_template('mapaa.html', title='Mapa')

I want to send jsonify(slownik) to my code in JavaScript but I dont want to do it with render_template bacause it refresh a page and I need this data to display it on the map using JavaScript.我想在jsonify(slownik)发送到我的代码,但我不想使用render_template执行此操作,因为它会刷新页面,我需要使用此数据在 map 上显示它I tried return jsonify(slownik) but it return me the data on new page.我尝试return jsonify(slownik)但它返回了新页面上的数据。 How I can send the data when the user click event_form button to JavaScript without refreshing page?当用户单击event_form按钮到 JavaScript 而不刷新页面时,如何发送数据?

You can use ajax for sending post request without refreshing the page.您可以使用 ajax 发送 post 请求而无需刷新页面。 Note- include jquery before this注意 - 在此之前包括 jquery

<script src="https://code.jquery.com/jquery-3.1.0.js" ></script>

javascript code javascript码

$("#id_of_btn").click(function () { // make ajax request on btn click
  $.ajax({
    type: "POST",
    url: "/mapaa", // url to the function
    data: {
      name: $("#id_of_input_tag").val(), // value of the form
    },
    success: function (response) {
      console.log(response); // response contains the json
    },
  });
});

make sure you don't use form tag.确保您不使用表单标签。

Edit: If you want to send more data via forms, you could use编辑:如果您想通过 forms 发送更多数据,您可以使用

data: $('form').serialize()

this will take the name attribute of input tag and add it in the request.data So if you have this这将获取输入标签的名称属性并将其添加到 request.data 所以如果你有这个

<input type="text" id="element_id" name="username" > 

You can use the value of name attribute like this request.data['username'] follow this tutorial您可以使用 name 属性的值,例如request.data['username']遵循本教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM