使用 jQuery 显示新的 Django 对象

发布于 2024-11-01 01:34:28 字数 820 浏览 2 评论 0原文

我一直在学习 Django + jQuery,到目前为止已经能够 AJAX 化新帖子功能。我现在的问题是如何在 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;

   })

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

谢谢你!

I've been learning Django + jQuery and so far have been able to AJAX-ify a New Post functionality. My question now is how do I display the new Post nicely and easily in the Post List 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")

So far I am able to return "success" and save the new Post just fine.

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;

   })

Just alerting "success" here, and that works fine. I can see the new Post in the Post List if I refresh the page. Now how do I load the new Post AJAX-ly? Do I have to grab Post's attributes and prepend them to my DIV manually? Is there an easy way to just reload my Post List?

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

感悟人生的甜 2024-11-08 01:34:28

为什么不直接在成功返回中返回帖子的 HTML,并使用 jQuery 将其附加到页面中应该放置的位置。这就是我通常在代码中所做的事情,既快速又简单。对于更复杂的解决方案,您可能希望返回 JSON 对象列表,并使用像backbone.js 这样的 JavaScript 框架

Why don't you just return the HTML for the post the in the success return, and use jQuery to append it to where it should go in your page. That's what I usually do in my code, it's quick and easy. For more complex solutions you'd want to return a list of JSON objects perhaps and use a javascript framework like backbone.js

烟若柳尘 2024-11-08 01:34:28

这是虚拟的方式;

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 从您的 json 对象捕获 < code>views.py,如果成功,则.append()将返回的post_instance对象添加到列表中。

Here's the dummy way;

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}))

At template part use $.getJSON or $.ajax to catch json object from your views.py and if it is success, .append() the returned post_instance object to the list.

吃素的狼 2024-11-08 01:34:28

在 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>

In your Django backend service, you need to give back some information related to the logic of your application. Mostly, people tend to use JSON for this.

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")

Your client side next to handle that response accordingly to the data written in the HttpResponse object.

   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";
    }

Make sure you handle both error and complete callbacks.

In the example I have given you'll need to have an HTML element with message as id, i.e:

<div id="message"></div>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文