django ajax json的實(shí)例代碼
1. views.py
定義views視圖函數(shù),將數(shù)據(jù)存入字典。并用壓縮為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數(shù)據(jù),并處理并添加到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("評(píng)論不能少于5個(gè)字") }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的實(shí)例代碼就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
pandas應(yīng)用實(shí)例之pivot函數(shù)詳解
最近在做基于python的數(shù)據(jù)分析工作,引用第三方數(shù)據(jù)分析庫(kù)pandas,所以下面這篇文章主要給大家介紹了關(guān)于pandas應(yīng)用實(shí)例之pivot函數(shù)的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07對(duì)Tensorflow中tensorboard日志的生成與顯示詳解
今天小編就為大家分享一篇對(duì)Tensorflow中tensorboard日志的生成與顯示詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02python生成以及打開(kāi)json、csv和txt文件的實(shí)例
今天小編就為大家分享一篇python生成以及打開(kāi)json、csv和txt文件的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11python政策網(wǎng)字體反爬實(shí)例(附完整代碼)
大家好,本篇文章主要講的是python政策網(wǎng)字體反爬實(shí)例(附完整代碼),感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下2022-01-01linux環(huán)境打包python工程為可執(zhí)行程序的過(guò)程
本次需求,在ubuntu上面開(kāi)發(fā)的python代碼程序需要打包成一個(gè)可執(zhí)行程序然后交付給甲方,因?yàn)椴荒苤苯咏o源碼給甲方,所以尋找方法將python開(kāi)發(fā)的源碼打包成一個(gè)可執(zhí)行程序,本次在ubuntu上打包python源碼的方法和在window上打包的有點(diǎn)類似,感興趣的朋友跟隨小編一起看看吧2024-01-01python登錄WeChat 實(shí)現(xiàn)自動(dòng)回復(fù)實(shí)例詳解
在本篇內(nèi)容里小編給大家整理的是關(guān)于python登錄WeChat 實(shí)現(xiàn)自動(dòng)回復(fù)的相關(guān)實(shí)例內(nèi)容以及知識(shí)點(diǎn)總結(jié),有興趣的朋友們參考下。2019-05-05