What are good modern patterns or django apps for handling server side forms that appear in a popup? By this I mean:
Assume common libraries like jquery or bootstrap 3 are available. Bonus points for DRY solutions: most patterns I've seen are kinda hairball, and the django ajax helpers I've looked into don't address the modal popup well or at all.
Here a way that uses plain jquery with a bootstrap styling the popup: See http://jsfiddle.net/brycenesbitt/afyY2/ . The trigger in a real app would look like:
$('#edit_foo').on('click', function () {
$.ajax({
type: 'GET',
url: '/ajax/fooForm/',
},
success: function (data, textStatus, jqXHR) {
$('#foo_modal').find('.modal-body').html(data);
$('#foo_modal').modal('show');
},
});
});
The ajax call is expected to return the necessary form as html (no json).
On submit you'll need a hack because the jquery ajax error function won't return data: If the return code is 204 "no content" clean up and exit. If the return code is 200 redisplay the form with server side error notes.
See also this nice, but code-heavy, live form validation: http://www.the-art-of-web.com/javascript/ajax-validate/ and this grid of django ajax tools https://www.djangopackages.com/grids/g/ajax/ , none of which I particujlarly recommend.
您可以查看https://www.djangopackages.com/grids/g/ajax/上的Django ajax工具网格。
This is how I did it:
$(document).on('submit', 'div.modal-body form', function(e) {
var form_el = $(this);
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function (xhr, ajaxOptions, thrownError) {
if ( $(xhr).find('.errorlist').length > 0 ) {
form_el.parents('.modal-body').html(xhr);
} else {
form_el.parents('.modal-body').html('<h4>Form was properly processed!</h4>');
}
},
error: function (xhr, ajaxOptions, thrownError) {
form_el.parents('.modal-body').html(xhr);
}
});
});
So basically what this does is:
form
element that is inside div.modal-body
(bootstrap modal). If that event fires, then it gets captured in here. $(this)
, so no need to hard code errorlist
that means an error occurred, so instead of redirecting I capture that and I update the form to show the form including its error messages.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.