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)文章
Python編程實(shí)戰(zhàn)之Oracle數(shù)據(jù)庫操作示例
這篇文章主要介紹了Python編程實(shí)戰(zhàn)之Oracle數(shù)據(jù)庫操作,結(jié)合具體實(shí)例形式分析了Python的Oracle數(shù)據(jù)庫模塊cx_Oracle包安裝、Oracle連接及操作技巧,需要的朋友可以參考下2017-06-06
python生成指定長(zhǎng)度的隨機(jī)數(shù)密碼
這篇文章主要介紹了python生成指定長(zhǎng)度的隨機(jī)密碼示例,密碼使用數(shù)字和字母組合,大家參考使用吧2014-01-01
python實(shí)現(xiàn)手機(jī)號(hào)歸屬地查詢功能
手機(jī)上突然收到了某銀行的短信提示,看了一下手機(jī)的位數(shù),正好是11位,我一想,這不就是標(biāo)準(zhǔn)的手機(jī)號(hào)碼嗎?于是想用python的庫實(shí)現(xiàn)查詢手機(jī)號(hào)碼歸屬地查詢自由,所以本文給大家介紹了如何用python實(shí)現(xiàn)手機(jī)號(hào)歸屬地查詢功能,需要的朋友可以參考下2024-03-03
Python Numpy數(shù)組擴(kuò)展repeat和tile使用實(shí)例解析
這篇文章主要介紹了Python Numpy數(shù)組擴(kuò)展repeat和tile使用實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12

