问题
I have a database with users. I can get the users email from the drop-down list to the modal window. using ajax.
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?
DB strcture:
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">×</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>
回答1:
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:
In the HTML:
Change value="{{descr}}"> to 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>
In that way only the email address is going to be sent back up when the Ajax call is made.
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()
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.
来源:https://stackoverflow.com/questions/62811205/getting-data-from-the-database-before-form-submitting