异步形式与引导和Django的 [英] Asynchronous forms with bootstrap and django

查看:137
本文介绍了异步形式与引导和Django的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我试图使这种形式asyncronous。理想情况下,我用这种形式来添加单位,然后动态地更新表。我不想整个页面刷新。我不是说所有的javascript好,我可以使用一些指针,这是怎么回事:

这几件事情正在发生,我不希望发生的事情:

  1. 在整个页面被刷新
  2. request.is_ajax()为假。

大多数时候,我只是想知道这是怎么回事,但问题是,我该如何改变下面来解决以上两个问题? (如果它们的问题是,在所有的问题。)

一些低于code是从这样一个问题:

<一个href="http://stackoverflow.com/questions/9979622/how-do-i-insert-a-django-form-in-twitter-bootstrap-modal-window?rq=1">How做我插入Twitter的引导模式窗口一个Django的形式?

有关的记录,我看到后只是罚款,request.POST,我只想让它工作Asyncronously,这是多么我的问题不同于以上。

  {%脚本块%}
&LT;脚本类型=文/ JavaScript的&GT;
    $(文件)。就绪(函数(){
        modalConnect();
    });
&LT; / SCRIPT&GT;

&LT;脚本类型=文/ JavaScript的&GT;
$(文件).ajaxStop(函数(){
    modalConnect();
});
&LT; / SCRIPT&GT;

&LT;脚本类型=文/ JavaScript的&GT;
    功能modalConnect()
        {
            //取消绑定click事件。如果不这样做,我们将结束与多个点击事件绑定,绑定以来每次Ajax调用后进行。
            $(。editItem)解除(点击);
            //绑定click事件
            $(editItem。)点击(函数(EV){//每个编辑项目&lt; A&GT;
                。EV preventDefault(); // prevent导航
                VAR URL = this.href; //从HREF的&lt; A&GT;元件
                $获得(网址功能(结果){
                  //获取表单
                  VAR itemForm = $(#ajax_form_modal_result,结果);
                  //获取更新网址
                  VAR formUpdateURLDiv = $(#formUpdateURL,结果);
                  //获取div的内部HTML
                  变种formUpdateURL = formUpdateURLDiv.html();
                  //更新与接收形式的DOM
                  $('#库存)HTML(itemForm);
                  //显示自举模式
                  $(#盘点)模式('秀')。
                  $(文件)。就绪(函数(){
                     //表单绑定到一个Ajax调用。 Ajax调用将被设置为接收更新URL
                     submitItemModalFormBind(formUpdateURL);
                  });
                },HTML);
                返回false; // prevent点击传播
            })
        }
&LT; / SCRIPT&GT;

&LT;脚本类型=文/ JavaScript的&GT;
       功能submitItemModalFormBind(URL){
         //绑定的形式。 prevent默认行为,并通过AJAX,而不是提交表单
         $('#ajax_form_modal_result)。递交(函数(EV){
             $阿贾克斯({
                键入:POST,
                网址:网址,
                数据:$(本).serialize()
                成功:函数(响应,textStatus,jqXHR){
                     变种形式= $(#ajax_form_modal_result_div,响应);
                     //如果它不是有效的形式被返回。更新模式与返回的形式
                     //改变这种如果,检查是否有具体的返回code,应在视图中设置
                     如果(form.html()){
                        的console.log('形式是无效的,并返回');
                        //更新模式格
                         $('#ajax_form_modal_result_div)HTML(表格);
                         $(#盘点)模式('秀')。
                      }
                      //形式不返回,如果表单提交成功
                      其他{
                        //更新以来,我们收到了整个成功页面接收到响应的整个文件,我们要重新加载整个页面

                        //排序修改日期倒序排列

                        // VAR notificationDiv = $(#的通知,响应);
                        // $('#通知)HTML(notificationDiv.html())。
                        的console.log('形式是有效的,并没有返回');
                        $(#盘点)模式(隐藏)。
                        }
                },
                错误:函数(请求,状态,错误){
                            VAR股利= $(ajax_form_modal_result_div,request.responseText);
                            $('#ajax_form_modal_result_div)HTML(DIV);
                            //执行正确的错误处理
                            的console.log(失败);
                            执行console.log(request.responseText);
                        }
                    });
                    返回false;
                });
              }
&LT; / SCRIPT&GT;



{%端嵌段%}

{%块含量%}

&LT; D​​IV CLASS =行&GT;
    &LT; D​​IV CLASS =span8 OFFSET4&GT;
        &LT; D​​IV CLASS =行&GT;
            &LT; D​​IV CLASS =span3&GT;
                &LT; H1&GT;
                收购
                &LT; / H1&GT;
            &LT; / DIV&GT;
            &LT; D​​IV CLASS =span3 OFFSET2&GT;
                &LT; H1&GT;
                &LT;一个ID =editItem的href =#盘点角色=按钮级=图标加号数据切换=模式&GT;&LT; / A&GT;
                加上单位
                &LT; / H1&GT;
            &LT; / DIV&GT;
        &LT; / DIV&GT;
        &LT;表类=表的表,悬停表条纹&GT;
            &LT; THEAD&GT;
                &其中; TR&GT;
                    &LT;第i个
                    大笑猫
                    &LT; /第i个
                &LT; / TR&GT;
            &LT; / THEAD&GT;
            &LT; TBODY&GT;
                &其中; TR&GT;
                    &LT; TD&GT;
                    大笑猫
                    &LT; / TD&GT;
                &LT; / TR&GT;
                    &其中; TR&GT;
                    &LT; TD&GT;
                    测试
                    &LT; / TD&GT;
                &LT; / TR&GT;
            &LT; / TBODY&GT;
        &LT; /表&gt;
    &LT; / DIV&GT;
&LT; / DIV&GT;


    &LT; D​​IV CLASS =模式隐藏变脸ID =盘点&GT;
&LT;形式ID =#ajax_form_modal_result级=好方法=邮报行动=&GT;
 &LT; D​​IV ID =ajax_form_modal_result_div&GT;


    &LT; D​​IV CLASS =模式的首部&GT;
    &LT;按钮式=按钮级=关闭数据解雇=莫代尔ARIA隐藏=真&GT;&安培;倍;&LT; /按钮&GT;
    &LT; H3&gt;添加单元&LT; / H3&GT;
    &LT; / DIV&GT;
    &LT; D​​IV CLASS =模态体&GT;
        {%csrf_token%}
         {{inventory.as_p}}

    &LT; / DIV&GT;
    &LT; D​​IV CLASS =模式躯&GT;
    &LT;按钮类=BTN数据解雇=莫代尔ARIA隐藏=真&GT;关闭&LT; /按钮&GT;
    &LT;输入类=BTN BTN-主型=提交值=保存/&GT;

    &LT; / DIV&GT;

   &LT; / DIV&GT;
&LT; /形式GT;
&LT; / DIV&GT;
 

解决方案

我可怕的AJAX挣扎时,我开始使用Django,由于缺乏JS经验。

我会给你一个aync形式我用它来添加选项和显示选项​​的一个例子。

我的模板模式code是如下,它的工作同样出色的形式被呈现,而不是我懒硬codeD的HTML。

 &LT; D​​IV CLASS =莫代尔ID =AddOptions的风格=显示:无;&GT;
  &LT; D​​IV CLASS =模式的首部&GT;
    &LT;按钮类=关闭数据解雇=模式&GT,X&LT; /按钮&GT;
    &LT; H3&gt;添加选项&LT; / H3&GT;
  &LT; / DIV&GT;
  &LT; D​​IV CLASS =模态体&GT;

&LT;形式ID =OptionForm行动=。方法='POST'&GT;
  &LT; D​​IV ID =OptionValueError级=控制组&GT;
  &LT;跨度类=求助在线&GT;&LT; / SPAN&GT;&LT; BR&GT;
  &LT; BR&GT;价值&安培; NBSP;&LT;输入类型=文本名称=OptionValueID =id_OptionValue/&GT;&LT; BR&GT;标签和放大器; NBSP;&LT;输入类型=文本名称=OptionLabel ID =id_OptionLabel/&GT;&LT;输入类型=隐藏名称=VariableID&GT;
  &LT; / DIV&GT;
&LT; D​​IV ID =divid_OptionTable&GT;
&LT;表类=表的表冷凝ID =OptionTable&GT;
&LT; THEAD&GT;
  &LT;第i个值小于/第i个
  百分位合并单元格=2&GT;标签&LT; /第i个
&LT; / THEAD&GT;
&LT; TBODY&GT;
&LT; / TBODY&GT;
&LT; /表&gt;
&LT; / DIV&GT;
&LT; / DIV&GT;
  &LT; D​​IV CLASS =模式躯&GT;
  &LT;输入类型=提交级=BTN BTN-主的价值=添加&GT;&安培; NBSP;&LT;按钮式=复位级=BTN&GT;复位&LT; /按钮&GT;
&LT; /形式GT;
  &LT; / DIV&GT;
&LT; / DIV&GT;
 

接下来,请确保以下是你照顾CSRF令牌的问题。

 &LT;脚本类型=文/ JavaScript的&GT;
jQuery的(文件).ajaxSend(函数(事件,XHR,设置){
    函数的getCookie(名字){
        VAR cookieValue = NULL;
        如果(document.cookie中和放大器;&安培;!的document.cookie =''){
            VAR饼干= document.cookie.split(';');
            对于(VAR I = 0; I&LT; cookies.length;我++){
                VAR饼干= jQuery.trim(饼干[I]);
                //这是否cookie字符串与我们想要的名字么?
                如果(cookie.substring(0,name.length + 1)==(名称+'=')){
                    cookieValue =去codeURIComponent(co​​okie.substring(name.length + 1));
                    打破;
                }
            }
        }
        返回cookieValue;
    }
    功能sameOrigin(URL){
        // URL可以是相对或计划相对或绝对
        VAR主机= document.location.host; //主机+端口
        VAR协议= document.location.protocol;
        VAR sr_origin ='//'+主机;
        变种起源=协议+ sr_origin;
        //允许以相同的起源绝对或相对方案网址
        返程(URL = = ||产地url.slice(0,origin.length + 1)==产地+'/')||
            (URL == sr_origin || url.slice(0,sr_origin.length + 1)== sr_origin +'/')||
            //或者说是不方案相对或即相对绝对的任何其他网址。
            !(/ ^(\ / \ / | HTTP:| HTTPS:。)* /测试(URL));
    }
    函数safeMethod(方法){
        返回(/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    如果(safeMethod(settings.type)及!&安培; sameOrigin(settings.url)){
        xhr.setRequestHeader(X-CSRFToken,的getCookie('csrftoken'));
    }
});
&LT; / SCRIPT&GT;
 

二,这是一个基本的AJAX POST会是什么样子使用jQuery。请注意,它是基于preventing的形式生活在我们的模式的默认提交的行为。上成功我追加新添加的值的表。这会减少麻烦,添加值追赶形式的一部分,但我想,以确保一切都被保存并处理被添加到表之前。

  $(文件)。就绪(函数(){
   $(#OptionForm)。递交(函数(事件){
       。事件preventDefault();
       $阿贾克斯({
            键入:POST,
            网址:{%URL builder.views.addoption%},
            数据:{VariableID:$('输入:隐藏[名称= VariableID])VAL(),OptionLabel:$('输入:文本[名称= OptionLabel])VAL(),OptionValue:$('输入:文[名称= OptionValue]')。VAL()},
            成功:功能(数据){
            的console.log(数据['OptionID']);
            $(#OptionValueError)removeClass移除(错误)。
            $(#OptionValueError跨越)文本()。
            $(#OptionValueError跨越)removeClass移除(错误)。
            $('#OptionTable&GT; TBODY:最后')追加('&LT; TR。 id=Option_'+data['OptionID']+'><td>'+data['OptionValue']+'</td><td>'+data['OptionLabel']+'</td><td><a HREF =#的onClick =deleteOption('+数据['OptionID'] +')&GT;&LT;我类=图标图标 - 去掉&GT;&LT; / I&GT;&LT; / A&GT;');
            $('输入:文本[名称= OptionValue])VAL('')。
            $('输入:文本[名称= OptionLabel])VAL('')。
            }
          });
       });
    });
 

最后,你只需要获取此AJAX请求,它看起来像下面这部分写了一个视图。

 高清addoption(要求):
    如果request.is_ajax():
        OptionValue = INT(request.POST ['OptionValue'])
        OptionLabel = request.POST ['OptionLabel']
        VariableID = INT(request.POST ['VariableID'])
        getVar = Variable.objects.get(ID = VariableID)
        newOption =选项(VariableID = getVar,
                值= OptionValue,
                标签= OptionLabel)
        newOption.save()
        响应= {'OptionValue:OptionValue,OptionLabel:OptionLabel,OptionID:newOption.id}
        JSON = simplejson.dumps(响应)
        返回的Htt presponse(JSON,MIMETYPE =文/ JSON)
    其他:
        通过
 

响应字典,我们是JSON序列化是反馈数据,随后用于追加值表。所有无需重新加载主页。

希望的例子帮助。让我知道,如果你有问题了。

JD

So i'm trying to make this form asyncronous. Ideally, I'm using this form to add units, and then update the table dynamically. I do not want the entire page to refresh. I'm not all that good with javascript, and I could use some pointers with what's going on:

A few things are happening that I don't want to happen:

  1. The entire page is refreshing
  2. request.is_ajax() is False.

Mostly, I'm just trying to understand what's going on, but the question is, how do I change the below to fix the above two issues? (if they are issues are issues at all.)

Some of the below code is taken from this question:

How do I insert a django form in twitter bootstrap modal window?

For the record, I am seeing the post just fine in request.POST, I just want to make it work Asyncronously, which is how my question differs from the above.

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

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

<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
                  $('#inventory').html(itemForm);
                  //show the bootstrap modal
                  $("#inventory").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>

<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,
                data: $(this).serialize(),
                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);
                         $("#inventory").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

                        //sort by modified date descending

                        //var notificationDiv = $("#notification", response);
                        //$('#notification').html(notificationDiv.html());
                        console.log('Form was valid and was not returned');
                        $("#inventory").modal('hide');
                        }
                },
                error: function (request, status, 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>



{% endblock %}

{% block content %}

<div class="row">
    <div class="span8 offset4">
        <div class="row">
            <div class="span3">
                <h1>
                Acquisitions
                </h1>
            </div>
            <div class="span3 offset2">
                <h1>
                <a id="editItem" href="#inventory" role="button" class="icon-plus-sign" data-toggle="modal"></a>
                Add Units
                </h1>
            </div>
        </div>
        <table class="table table-hover table-striped">
            <thead>
                <tr>
                    <th>
                    lolcats
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                    lolcats
                    </td>
                </tr>
                    <tr>
                    <td>
                    test
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>


    <div class="modal hide fade" id="inventory" >
<form id="#ajax_form_modal_result" class="well" method="post" action="">
 <div id="ajax_form_modal_result_div">


    <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h3>Add units</h3>
    </div>
    <div class="modal-body">
        {% csrf_token %}
         {{inventory.as_p}}

    </div>
    <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <input class="btn btn-primary" type="submit" value="Save" />

    </div>

   </div>
</form>
</div>

解决方案

I struggled horribly with AJAX when I started with Django due to a lack of JS experience.

I will give you an example of an aync form I use to add options and display the options.

My template modal code is as follows, and it will work just as well with the form being rendered rather than my lazy hardcoded html.

   <div class="modal" id="AddOptions" style="display:none;">
  <div class="modal-header">
    <button class="close" data-dismiss="modal">X</button>
    <h3>Add Options</h3>
  </div>
  <div class="modal-body">

<form id="OptionForm" action="." method='POST'>
  <div id="OptionValueError" class="control-group">
  <span class="help-inline"></span><br>
  <br>Value&nbsp;<input type="text" name="OptionValue" id="id_OptionValue" /><br>Label&nbsp;<input type="text" name="OptionLabel" id="id_OptionLabel"/><input type="hidden" name="VariableID">
  </div>
<div id="divid_OptionTable">
<table class="table table-condensed" id="OptionTable">
<thead>
  <th>Value</th>
  <th colspan="2">Label</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
  <div class="modal-footer">
  <input type="submit" class="btn btn-primary" value="Add">&nbsp;<button type="reset" class="btn">Reset</button>
</form>
  </div>
</div>

Next, make sure that the following is in your to take care of CSRF token issues.

<script type="text/javascript"> 
jQuery(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});
</script>

Second, this is what a basic AJAX POST would look like using jQuery. Notice it is based on preventing the Default submission behaviour of the form living in our modal. On success I am appending the newly added values to the table. It would be less troublesome to add the values as part of catching the form, but I like to be sure everything has been saved and processed before being added to the table.

   $(document).ready(function() {
   $("#OptionForm").submit(function(event){
       event.preventDefault();
       $.ajax({
            type:"POST",
            url:"{% url builder.views.addoption %}",
            data: {VariableID: $('input:hidden[name=VariableID]').val(), OptionLabel: $('input:text[name=OptionLabel]').val(), OptionValue: $('input:text[name=OptionValue]').val()},
            success: function(data){
            console.log(data['OptionID']);
            $("#OptionValueError").removeClass("error");  
            $("#OptionValueError span").text("");  
            $("#OptionValueError span").removeClass("error");
            $('#OptionTable > tbody:last').append('<tr id=Option_'+data['OptionID']+'><td>'+data['OptionValue']+'</td><td>'+data['OptionLabel']+'</td><td><a href="#" onClick="deleteOption('+data['OptionID']+')"><i class="icon icon-remove"></i></a>');
            $('input:text[name=OptionValue]').val('');
            $('input:text[name=OptionLabel]').val('');
            }
          });
       });
    });

Lastly, you just need the view that captures this AJAX request, which would look like this partially written one below.

def addoption(request):
    if request.is_ajax():
        OptionValue = int(request.POST['OptionValue'])
        OptionLabel = request.POST['OptionLabel']
        VariableID = int(request.POST['VariableID'])
        getVar = Variable.objects.get(id=VariableID)
        newOption = Option(VariableID=getVar,
                Value=OptionValue,
                Label=OptionLabel)
        newOption.save()
        response = {'OptionValue': OptionValue, 'OptionLabel': OptionLabel, 'OptionID': newOption.id}
        json = simplejson.dumps(response)
        return HttpResponse(json, mimetype="text/json")
    else:
        pass

The response dict that we are json serializing is what is fed back as data and subsequently used to append the values to the table. All without reloading the main page.

Hopefully the example helped. Let me know if you have anymore questions.

JD

这篇关于异步形式与引导和Django的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆