提交表单之前从数据库获取数据 [英] Getting data from the database before form submitting

查看:71
本文介绍了提交表单之前从数据库获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含用户的数据库.我可以从下拉列表到模式窗口中找到用户email.使用ajax.

I have a database with users. I can get the users email from the drop-down list to the modal window. using ajax.

问题是如何通过同一个模态窗口中的用户email接收该用户的born_date phone_number,然后发送该表格进行处理.某些功能无效.可能是什么错误?

The question is how to receive born_date and phone_number of this user via his email in the same modal window, and then send the form for processing. Something doesn’t work. What could be the mistake?

数据库结构:

python:

description = ['mymail@gmail','mymail@gmail','uuser@mail.ru','mymail2222@gmail','my1212mail@gmail','11mymail@gmail']


@app.route('/profile', methods=['GET'])
def profile():
    if request.method == 'GET' and 'loggedin' in session:
        cur = mysql.connection.cursor()
        cur.execute("SELECT firstname, lastname, email FROM users.data WHERE description = 'description'")
        account = cur.fetchall()
        description = account
        return render_template('profile.html', id=session['id'], email=session['email'],
                                                firstname=session['firstname'], description=description)


@app.route('/profile', methods=['POST'])
def profile_post():
    data = request.json
    data_list = list(data.values())

    data_list = str(data_list)
    doc_data = data_list.split()[2][:-4]

    cur = mysql.connection.cursor()
    cur.execute("SELECT born_date, phone_number FROM users.data WHERE email = '%s'" % doc_data.replace("'", ""))
    account = cur.fetchone()

born = account[0]
num = account[1]


    print('Got data:', data)
    return jsonify({
        'status': 'SUCCESS',
        'data': data,
    })


return render_template('profile.html', id=session['id'], born=born, num=num) 

html

<select id='sel' name='sel' class="selectpicker sel" multiple data-live-search="true" onchange="optionClick(this)">
    {% for descr in description%}
        <option id="val" value="{{descr}}">{{ descr }}</option>
    {% endfor %}
</select>
<button type="button" class="btn btn-primary" onclick="process();">
    Process
</button>

<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle" style='font-family: "Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, Verdana, sans-serif; font-size: 18px;'>Information about user</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p class="form-control" id="mySelectedValue" style="margin-top: 10px;"></p>


        <h2 class="white-text" style="font-size: 14px; color: #000;">Born date is: {{ born }}</h2>
        <h2 class="white-text" style="font-size: 14px; color: #000;">Phone number is: {{ num }}</h2>


        <button class="btn btn-primary">
            Send Data
        </button>
      </div>
    </div>
  </div>
</div> 
    


<script type="text/javascript">
function printValue(selectedItem) {
    $('#mySelectedValue').html(selectedItem.value.replace(/[{()}]/g, '').replace(/['"]+/g, '').replace(/[{,}]/g, ''));
    console.log(typeof(selectedItem.value));
}
function process(selectedItem) {
    $('#exampleModalCenter').modal('show')
    document.getElementById('#exampleModalCenter')
    const data = JSON.stringify({
        "selectedItems": $('#sel').val()
    });
    $.ajax({
        url: "/profile",
        type: "POST",
        contentType: "application/json",
        data: data,
        success: function (data) {
          console.log(data);
        },
    });
}
function optionClick(selectedItem) {
    printValue(selectedItem);
}
</script>

推荐答案

没有打印出电子邮件地址的实际参数,我不确定是什么错误,但是由于您没有得到例外,我只能猜测您使用的是数据库中不存在的值,因此您无法通过以下方式将电子邮件地址与输入正确分开:

Without your printing out what your actual argument is for the email address I can't be sure what the error is, but since you are not getting an exception I can only guess you are using a value that does not exist on the database and hence you are not separating the email address out correctly from the input using what amounts to:

email_address = data_list.split()[2][:-4].replace("'", "")

所以我的建议是进行以下更改:

So my suggestion is to make the following changes:

在HTML中:

value="{{descr}}">更改为value="{{descr['email']}}">:

<select id='sel' name='sel' class="selectpicker sel" multiple data-live-search="true" onchange="optionClick(this)">
    {% for descr in description%}
        <option id="val" value="{{descr['email']}}">{{ descr }}</option>
    {% endfor %}
</select>

通过这种方式,在拨打Ajax时仅备份电子邮件地址.

In that way only the email address is going to be sent back up when the Ajax call is made.

然后您的Python代码变为:

Your Python code then becomes:

data = request.json
email_address = data['selectedItems'][0] # the first email address selected
cur = mysql.connection.cursor()
cur.execute("SELECT born_date, phone_number FROM users.data WHERE email = %s", (email_address,))
account = cur.fetchone()

我相信,因为您有一个多选下拉菜单,即使列表仅包含一个项目,您也会收到一系列值的列表,这就是为什么我指定了data['selectedItems'][0]的原因.当然,显而易见的问题是,如果用户选择了多个电子邮件地址,则您的代码似乎无法处理此问题,因此我不知道您为什么将其设置为多选下拉列表.另请注意,我使用的是prepared statement,因此SQL注入攻击不再是问题.

I believe because you have a multi select dropdown that you will be sent up a list of values even if the list only contains a single item and that's why I have specified data['selectedItems'][0]. Of course, the obvious question is if the user has selected multiple email addresses, your code does not seem to handle this, so I don't know why you have made this a multi select dropdown. Note also that I am using a prepared statement so SQL Injection attacks should no longer be a problem.

这篇关于提交表单之前从数据库获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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