时间:2021-05-23
1. views.py
定义views视图函数,将数据存入字典。并用压缩为json格式,dumps,并return。
import jsondef 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的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
jQuery的ajax和遍历数组json实例代码jQuery.ajax({type:"POST",url:"server.json",dataType:'jso
php+ajax+json实例代码html页面:$(function(){$("#send").click(function(){varcont=$("inpu
原生ajax处理json格式数据代码实例:由于jQuery的出现,原生ajax使用频率也越来越少,这当然是因为jQuery的便利性多导致的。但是对于原生ajax
晚上在修改代码,之前用的复制代码代码如下:$.ajax({..dataType:'json',...success:function(json){//不执行su
本文实例讲述了ThinkPHP通过AJAX返回JSON的两种实现方法。分享给大家供大家参考。具体方法如下:方法一:php代码如下:复制代码代码如下:$arr=a