首页 文章

用jQuery显示新的Django对象

提问于
浏览
1

我一直在学习Django jQuery,到目前为止已经能够使用AJAX-ify一个新帖子功能 . 我现在的问题是如何在邮政列表AJAX-ly中轻松,轻松地显示新帖子?

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;

   })

只是在这里提醒“成功”,这很好 . 如果我刷新页面,我可以在帖子列表中看到新帖子 . 现在我如何加载新的Post AJAX-ly?我是否必须手动获取Post的属性并将其添加到我的DIV中?有没有一种简单的方法来重新加载我的帖子列表?

谢谢!

3 回答

  • 0

    为什么不在成功返回中返回post的HTML,并使用jQuery将其追加到页面中的位置 . 这就是我通常在我的代码中所做的事情,它快速而简单 . 对于更复杂的解决方案,您可能希望返回一个JSON对象列表,并使用像backbone.js这样的javascript框架

  • 3

    这是虚拟方式;

    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 对象,如果它是 success.append() 将返回的 post_instance 对象添加到列表中 .

  • 1

    在您的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 回调 .

    在我给你的例子中,你需要一个带有 message 作为id的HTML元素,即:

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

相关问题