jquery ajax/django – 在bootstrap模式中显示当前表单并重新显示验证是否成功

前端之家收集整理的这篇文章主要介绍了jquery ajax/django – 在bootstrap模式中显示当前表单并重新显示验证是否成功前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的用例是:

a)在引导模态fancy overlay effect stuff..中呈现通过ajax加载的表单.我跟着这些instructions.

这很好用. (见下面的代码)

b)将此表单提交回我的Django应用程序,尝试验证它,如果它没有验证,重新显示带有奇特引导模式中的错误的表单.

我可以通过ajax重新加载表单,但我无法在模态中再次表示它.

注意:我没有包含视图,因为它没有什么特别之处.仅实例化和验证表单.

下面有很多东西要读,所以如果您认为用例听起来很有趣,请继续…

我的taskList.html看起来像这样:

<table id="listItemTable" class="table table-bordered">
        <thead>
            <tr>
                <th>Name</th>
                <th>Edit</th>
            </tr>
        </thead>
    <tbody>
        <tr>
            <td>Task 1</td>
            <td><a class="editItem" href="/update/item/1/">edit</a></td>
        </tr>
    </tbody>
</table>

<div class="modal hide" id="itemFormModal"></div>
<div id="modalExtraJsPlaceholder"></div>

.js用于将显示引导模式绑定表单的表单加载到.jquery提交调用

$(document).ready(function() {
   modalConnect();
});

<script type="text/javascript">
 //connects the modal load for each <a> with class editItem
 //Functionality 1
     //loads an item edit form from the server and replaces the itemFormModal with the form
     //presents the modal with $("#itemFormModal").modal('show');
 //Functionality 2
     //loads some extra js "modalExtraJsHtml"
     //calls the function "submitItemModalFormBind" which has been loaded via "modalExtraJsHtml"

 function modalConnect(){
    $(".editItem").click(function(ev) { // for each edit item <a>
    ev.preventDefault(); // prevent navigation
    url = ($(this)[0].href); //get the href from <a>
    $.get(url,function(results){
       var itemForm = $("#ajax_form_modal_result",results);
       var modalExtraJs = $("#modalExtraJs",results);
       //get the html content
       var modalExtraJsHtml = modalExtraJs.html();
       //update the dom with the received results
        $('#itemFormModal').html(itemForm);        
        $('#modalExtraJsPlaceholder').html(modalExtraJsHtml);
        $("#itemFormModal").modal('show');
        submitItemModalFormBind(); //bind loaded form to ajax call
     },"html");
     return false; // prevent the click propagation
   })
}
</script>

从视图返回的itemForm如下所示:

<form id="#ajax_form_modal_result" class="well" method="post" action="/update/item/{{ item.id }}">
 <div id="ajax_form_modal_result_div">
     <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">×</button>
      <h3>Edit Item</h3>
    </div>
    <div class="modal-body">
         {% csrf_token %}
         {{form.as_p}}
    </div>
    <div class="modal-footer">
         <input class="btn btn-primary" type="submit" value="Save" />
         <input name="cancel" class="btn" type="submit" value="Cancel"/>
     </div>
    </div>
</form>

加载和显示模态工作正常.
但现在第二部分没有达到预期的效果.问题如下.如果表单未验证,则视图将返回表单.返回的表单应该在bootstrap模式中再次显示.但结果是,只有表单在浏览器中显示,其他一切都丢失了.没有CSS,没有表,只有表格.相当丑陋..因此我没有实现更新ajax_form_modal_result_div.任何人都可以帮我解决我做错了什么..!?

该视图还返回js函数’submitItemModalFormBind’,它阻止表单默认行为并通过ajax发送表单.

<div id="modalExtraJs">
 //ajax bind for update item form visualized via modal
 function submitItemModalFormBind(){
     var url = "{% url updateItem item.pk %}";
     $('#ajax_form_modal_result').submit(function(){
 $.ajax({
    type: "POST",url: "{% url updateTask item.pk %}",data: $(this).serialize(),success:function(response){
        var div = $("ajax_form_modal_result_div",response);
        $('#ajax_form_modal_result_div').html(div);
     },error: function (request,status,error) {
         console.log("failure");
         console.log(request.responseText);
     }

           });
          });
        return false;
       }    
</div>

解决方法

找到了一种工作方法(基于这个 solution – 并通过处理无效形式对其进行了强化)并将其发布给任何想要使用django的令人惊叹的漂亮引导模态的人.上面代码的主要问题是我没有正确地禁用提交按钮的默认行为,并且加载其他js的方法不是一个好主意.所以我改变了策略.

在documentReady或ajaxStop事件上,将超链接的click事件绑定到modalConnect函数.请注意,如果你有某种更新表格内容的ajax(我有),你只需要ajaxStop函数

<script type="text/javascript">
    $(document).ready(function() {
        modalConnect();
    });
</script>

<script type="text/javascript">
$( document ).ajaxStop( function() {
    modalConnect();
});
</script>

modalConnect函数加载我们想要在模态中呈现的表单和formUpdateURLDiv:

<script type="text/javascript">
    function modalConnect()
        {
            //unbind the click event. If not done we will end up with multiple click event bindings,since binding is done after each ajax call.
            $(".editItem").unbind('click');
            //bind the click event
            $(".editItem").click(function(ev) { // for each edit item <a>
                ev.preventDefault(); // prevent navigation
                var url = this.href; //get the href from the <a> element
                $.get(url,function(results){
                  //get the form
                  var itemForm = $("#ajax_form_modal_result",results);
                  //get the update URL
                  var formUpdateURLDiv = $("#formUpdateURL",results);
                  //get the inner html of the div
                  var formUpdateURL = formUpdateURLDiv.html();
                  //update the dom with the received form
                  $('#itemFormModal').html(itemForm);
                  //show the bootstrap modal
                  $("#itemFormModal").modal('show');
                  $(document).ready(function () {
                     //bind the form to an ajax call. ajax call will be set to the received update url
                     submitItemModalFormBind(formUpdateURL);
                  });
                },"html");
                return false; // prevent the click propagation
            })
        }
</script>

formUpdateURL包括生成的服务器(参见下面的包含视图)url,加载的表单必须对其进行表单提交调用.我们使用这个url来“初始化”submitItemModalFormBind函数

<script type="text/javascript">
       function submitItemModalFormBind(url){
         //bind the form. prevent default behavior and submit form via ajax instead
         $('#ajax_form_modal_result').submit(function(ev){
             $.ajax({
                type: "POST",url: url,success:function(response,textStatus,jqXHR){
                     var form = $("#ajax_form_modal_result_div",response);
                     //form is returned if it is not valid. update modal with returned form
                     //change this "if" to check for a specific return code which should be set in the view
                     if (form.html()) {
                        console.log('Form was invalid and was returned');
                        //update modal div
                         $('#ajax_form_modal_result_div').html(form);
                         $("#itemFormModal").modal('show');
                      }
                      //form is not returned if form submission succeeded
                      else{
                        //update the entire document with the response received since we received a entire success page and we want to reload the entire page
                        document.open();
                        document.write(response);
                        document.close();
                        //sort by modified date descending

                        //var notificationDiv = $("#notification",response);
                        //$('#notification').html(notificationDiv.html());
                        console.log('Form was valid and was not returned');
                        $("#itemFormModal").modal('hide');
                        }
                },error) {
                            var div = $("ajax_form_modal_result_div",request.responseText);
                            $('#ajax_form_modal_result_div').html(div);
                            //implement proper error handling
                            console.log("failure");
                            console.log(request.responseText);
                        }
                    });
                    return false;
                });
              }
</script>

..并查看服务器上发生了什么,请参阅下面处理逻辑的视图:

class UpdateTaskModalView(LoginrequiredMixin,View):
template = 'list_management/crud/item/update_via_modal.html'

def get_logic(self,request,task_id,**kwargs):
    task = get_object_or_404(Task.objects,pk=task_id)
    task_form = TaskForm(instance=task)
    context = {
               'model_form': task_form,'item': task,}
    return context

def post_logic(self,pk=task_id)
    task_form = TaskForm(request.POST,instance=task)
    if task_form.is_valid():
        task = task_form.save(commit=False)
        task.modified_by = request.user
        task.save()
        messages.add_message(request,messages.INFO,'Item "%s" successfully updated' % (task.name))
        return ('redirect',HttpResponseRedirect(reverse('show_list_after_item_update',kwargs={'list_id':task.list.pk,'item_id':task.pk})))
    context = {
        'model_form' : task_form,'list': task.list,}
    return ('context',context)

def get(self,**kwargs):
    context = self.get_logic(request,**kwargs)
    return render_to_response(
        self.template,context,context_instance = RequestContext(request),)

def post(self,**kwargs):
    post_logic_return = self.post_logic(request,**kwargs)
    if post_logic_return[0] == 'redirect':
        return post_logic_return[1]
    if post_logic_return[0] == 'context':
        context = post_logic_return[1]
        return render_to_response(
            self.template,)

..表单模板已包含在我的问题中:ajax_form_modal_result_div,您只需要提供formUpdateURL.我是通过模板完成的,现在我写这篇文章似乎很奇怪.可以通过视图上下文轻松提供.

Voila – 带有Bootstrap模式的Django表单!增加你的UI!

我希望这有助于某人解决类似的问题.

原文链接:https://www.f2er.com/jquery/181426.html

猜你在找的jQuery相关文章