django ajax json的實例代碼
更新時間:2018年05月29日 08:43:12 作者:q493383189
今天就為大家分享一篇django ajax json的實例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
1. views.py
定義views視圖函數,將數據存入字典。并用壓縮為json格式,dumps,并return。
import json def get_comments(request, article_id): article_obj = models.Article.objects.get(id=article_id) article_comments = article_obj.comment_set.select_related() comment_dict = {} for i in article_comments: print('comments_id', i.id) print('article_id', i.article_id) print('parent_comment_id', i.parent_comment_id) print('comment_type', i.comment_type) print('user_id', i.user_id) print('user_name', i.user.name) print('comment', i.comment) print('date', type(i.date)) print('date', time.strftime("%Y-%m-%d %H:%M:%S", i.date.timetuple())) comment_dict[i.id] = [i.comment_type, i.comment, time.strftime("%Y-%m-%d %H:%M:%S", i.date.timetuple()), i.article_id, i.user_id, i.user.name, i.parent_comment_id] comment_json = json.dumps(comment_dict) return HttpResponse(comment_json)
2. article.html中編輯js jquery,接受json數據,并處理并添加到html中
<script> function getComments() { $.get("{% url 'get_comment' one_article.id %}", function(callback){ console.log(callback); var obj = JSON.parse(callback); console.log(this.comment_type); for (var key in obj){ console.log(key); console.log(obj[key]) } } function getCsrf() { return $("input[name='csrfmiddlewaretoken']").val(); } $(document).ready(function () { $(".comment-box button").click(function () { var comment_text = $('.comment-box textarea').val(); if (comment_text.trim().length < 5){ alert("評論不能少于5個字") }else { $.post( "{% url 'post_comment' %}", { 'comment_type':1, article_id: "{{ one_article.id }}", parent_comment_id:null, 'comment':comment_text.trim(), 'csrfmiddlewaretoken':getCsrf() }, function (callback) { console.log(callback); if (callback == 'post-comment-success'){ alert('post-comment-success'); getComments(); } } ) } }) }) </script>
以上這篇django ajax json的實例代碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
對Tensorflow中tensorboard日志的生成與顯示詳解
今天小編就為大家分享一篇對Tensorflow中tensorboard日志的生成與顯示詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02linux環(huán)境打包python工程為可執(zhí)行程序的過程
本次需求,在ubuntu上面開發(fā)的python代碼程序需要打包成一個可執(zhí)行程序然后交付給甲方,因為不能直接給源碼給甲方,所以尋找方法將python開發(fā)的源碼打包成一個可執(zhí)行程序,本次在ubuntu上打包python源碼的方法和在window上打包的有點類似,感興趣的朋友跟隨小編一起看看吧2024-01-01python登錄WeChat 實現(xiàn)自動回復實例詳解
在本篇內容里小編給大家整理的是關于python登錄WeChat 實現(xiàn)自動回復的相關實例內容以及知識點總結,有興趣的朋友們參考下。2019-05-05