ajax在django中的应用

jQuery安装下载到本地或者直接引用:

<head> <script src="***/jquery.min.js" rel="nofollow"/></head>
<div id = "reply_form" style="background-color: #E8E8E8"> 
    {% for dic_reply in reply_message %} 
        {% ifequal dic_reply.parent_id_id dic.id %}
             <p> <b>回复人:</b>{{dic_reply.user_name}} 
             <b>时间:</b> {{dic_reply.time}} </p> 
             <p> <b>内容:</b>{{dic_reply.content}} </p> 
         {% endifequal %} 
     {% endfor %} 
</div>
因为Django无法通过render_to_response方法局部加载html,如果django只是通过HttpResponse传递一个变量,jQuery无法局部加载和template变量也无法渲染template模板  
    后来想到两思路:
        1. 后台直接构成一个完整html格式内容,传给前端直接替换。
        2.后台只传变量到前端,通过js方法构成想要的html格式内容,再做替换。
        其实两种方法区别就是一种在后台完成html内容构造,一种在前端构造。试验了很多次,没能成功,最后在高手指点下终于成功试出方法1。基本思路还是在后台先生成正确的html格式代码,在统一发到前端替换前端代码。


if request.is_ajax(): 
    t = get_template('reply_form.html') //获取模板内容 
    content_html = t.render(Context({'reply_message':ReplyMessage_dic})) //渲染模板生成想要的局部html内容 
    payload = { 
        'content_html': content_html, 
        'success': True} //构造json类型数据,以方便前端处理 
    return HttpResponse(json.dumps(payload), mimetype="application/json") //用json类型返回数据到前端



    这地方要注意的问题是渲染模板不能用render_to_response的方法,否则就直接返回到前端了。返回HttpResponse一定要加mimetype="application/json"参数,否则可能会出现前端页面无法通过json的方法获取到对应的值前端JS代码:
     <script type="text/javascript"> 
        $(document).ready(function() { 
            $('#reply_submit').submit(function() { // catch the form's submit event 
                $.ajax({ // create an AJAX call... 
                    data: $(this).serialize(), // get the form data 
                    type: $(this).attr('method'), // GET or POST 
                    url: $(this).attr('action'), // the file to call; send the data to server 
                    success:function(responseData) { // on success.. get respose from the server 
                    $('#reply_form').html(responseData.content_html); // update the DIV with response 
                    }
                 }); 
                return false; 
            });
        }); 
     </script> 
     
     几点说明的:
        1.responseData就是后台传过来的json类型数据,即我们构造的payload,有点python里面字典数据类型,实际上通过json.dump方法传递后已经是一个json数据类型。这样方便前端用json方法访问。而responseData.content_html就是我们要替换实际内容。个人对json的理解是Ajax用来前后台方便通信的一种数据类型,具体介绍可以上W3c去查阅。
        2. 调式前端问题可以通过firebug,fiddler等工具调试(比较菜)。


转载于:https://my.oschina.net/shniu/blog/290130

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值