我花了好几天才走到这一步,我希望有人可以在最后阶段帮助我。我在一个模态中有一个表单,我希望用ajax发布到一个php文件。我是jquery的新手,我试图弄清楚如何让这两个jquery一起工作。
请参阅fiddle
表格和模态
<a href="#my_modal" data-toggle="modal" data-review="submit this information to database">Open Modal</a>
<div class="modal" id="my_modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Modal header</h4>
</div>
<div class="modal-body">
<form>
<p>some content</p>
<input type="text" name="review" value=""/>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Jquery
//Variable is passed to modal
$('#my_modal').on('show.bs.modal', function(e) {
var review = $(e.relatedTarget).data('review');
$(e.currentTarget).find('input[name="review"]').val(review);
});
//Now post my form with the following ajax code when Modal Submit button is pressed.
$.post('insert.php', {review: review},
function(data){
$('#myModal').modal('hide');
$("#message").html(data);
$("#message").fadeIn(500);
$("#message").fadeOut(2500);
});
答案 0 :(得分:0)
将按钮类型更改为buttton
,而不是提交并添加标识符,以便您可以使用javascript click事件控制点击,替换:
<button type="submit" class="btn btn-primary">Save changes</button>
by:
<button type="button" class="btn btn-primary" id='submit-form'>Save changes</button>
然后在按钮上添加点击evetn:
$('body').on('#submit-form', 'click', function(){
var review = $('input[name="review"]').val();
$.post('insert.php', {review: review},
function(data){
$('#myModal').modal('hide');
$("#message").html(data);
$("#message").fadeIn(500);
$("#message").fadeOut(2500);
});
})
答案 1 :(得分:0)
将模态页脚和模态体保持在表单标记内。 添加id以提交按钮,然后进行ajax调用。
$("#submitButtonId").on("click",function(){
//Ajax call here
}
答案 2 :(得分:0)
请使用这样的js代码。
$('.btn').click(function(e) {
var review = $(this).find("input[name=review]").val();
var request = $.ajax({
url: "insert.php",
method: "POST",
data: { review: review },
dataType: "html"
});
})