溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

django ajax json的實(shí)例代碼

發(fā)布時(shí)間:2020-09-12 17:20:52 來(lái)源:腳本之家 閱讀:142 作者:q493383189 欄目:開(kāi)發(fā)技術(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è)參考,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI