我有一个表单通过Ajax提交后端进程(Flask应用程序),然后在数组中返回响应。如何打开模态并在响应中传递数据?
<script>
$(document).ready(function() {
$("#myButton").click(function(event) {
$.ajax({
url: '/get_data',
type: 'POST',
data: myFormData,
success: function(AjaxResponse){
console.log(AjaxResponse);
$('#myModal').modal('show'); //open modal and pass AjaxResponse to it
}
});
});
});
</script>
后端流程
@app.route('/get_data',methods=['POST'])
def get_data():
if request.method == 'POST':
'''
use myFormData to request data from database
returns result in array
response = ["Red", "Green", "Blue", "Black"]
'''
return jsonify(response)
模态:
<div class="modal" tabindex="-1" role="dialog" id="myModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{% for item in AjaxResponse %}
<label>{{item}}</label>
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
答案 0 :(得分:0)
如果返回json结果是一个选项,那么你可以这样做:
when
不确定您正在使用哪个服务器端代码...如果使用ASP.NET MVC,您可以在服务器端构建HTML并在局部视图中返回它。您的ajax调用需要获取部分视图并替换它:See here for explanation
答案 1 :(得分:0)
试试这个
$.ajax({
url: '/get_data',
dataType: 'json',
type: 'POST',
data: myFormData,
success: function(data){
var items = '';
var label = '';
$.each(data, function (i, item) {
// build your html here and append it to your .modal-body
label = "<label>" + item.MyProperty+ "</label>"
});
$('div.modal-body').append(label);
}
});