用jQuery显示新的Django对象

1 投票
3 回答
681 浏览
提问于 2025-04-16 15:33

我最近在学习Django和jQuery,目前已经成功实现了通过AJAX功能来添加新帖子。现在我想知道,怎么才能把新帖子漂亮又简单地显示在帖子列表里呢?

views.py:

def add_post(request):
error_msg = u"No POST data sent."
post = Post()
if request.method == "POST":
    #do stuff

return HttpResponse("success")

到目前为止,我可以返回“成功”并且顺利保存新帖子。

jQuery:

       $("form#add_post").submit(function() {
       //do stuff
       var args = {type:"POST", url:"add_post/", data:data, complete:function(res, status) {
            if (status == "success") {
                alert("success");
            } else {

            }
        }};

       $.ajax(args);

       return false;

   })

在这里我只是弹出了一个“成功”的提示,这个没问题。如果我刷新页面,就能看到新帖子。那么,怎么才能通过AJAX加载新帖子呢?我是不是得手动获取帖子的属性,然后把它们加到我的DIV里?有没有简单的方法可以直接重新加载我的帖子列表呢?

谢谢!

3 个回答

0

在你的Django后台服务中,你需要返回一些与应用逻辑相关的信息。大多数情况下,人们会选择使用JSON格式来传递这些信息。

def add_post(request):
   error_msg = u"No POST data sent."
   post = Post()
   if request.method == "POST":
      #do stuff
      response = HttpResponse(content_type = 'application/javascript')
      data = dict()
      #here it comes your logic
      #that fills 'data' with whichever 
      #information you need.
      data['message']='post added !!'
      response.write(json.dumps(data))
      return response
   else:
      return HttpResponse("NO POST REQUEST HANDLE")

你的客户端需要根据HttpResponse对象中写的数据来处理这个响应。

   complete: function(res, status) {
            //In here you can do whatever you want to modify your
            //HTML dynamically
            // the variable res contains the JSON object dumped in the
            // django HTTPResponse object.
            $("#message").text = res['message'];
    }

   error: function(res, status) {
            $("#message").text = "error handling ajax request";
    }

确保你处理好errorcomplete这两种回调情况。

在我给出的例子中,你需要有一个HTML元素,它的id是message,也就是说:

<div id="message"></div>
1

这里有个简单的方法;

views.py 文件:

def add_post(request):
    error_msg = u"No POST data sent."
    post_instance = Post()
    if request.method == "POST":
        # I love Rock'nRoll
        return post_instance

 return HttpResponse(json.dumps({'status': 'success', 'object': post_instance}))

在模板部分,可以使用 $.getJSON$.ajax 来获取你在 views.py 中返回的 json 对象。如果获取成功,就用 .append() 把返回的 post_instance 对象添加到列表里。

3

你为什么不直接在成功返回的时候把帖子对应的HTML代码返回,然后用jQuery把它加到页面应该放的位置呢?我在代码里通常都是这么做的,这样又快又简单。如果要处理更复杂的情况,可能就需要返回一组JSON对象,然后用像backbone.js这样的JavaScript框架来处理。

撰写回答