weixin_33736048 2017-05-25 00:12 采纳率: 0%
浏览 77

Django Ajax GET请求

i'm very very new to jquery and ajax and right now i've already built a django forum-app whereby on the homescreen, the left side displays the list of forumposts and the right side is blank. Because i'm new to AJAX, i've built my django app in such a way that whenever I click on any of the forumposts displayed on the left, it will redirect me into a details page which shows the content of that post. However, I want to improve the user experience by using AJAX such that whenever I click on any forumpost on the left, the blank space on the right will be updated and display the contents of that specific post.

But i'm not quite sure how to begin because i'm new to jquery/ajax. Can somebody help me? Thank you!

  • 写回答

1条回答 默认 最新

  • weixin_33747129 2017-05-25 00:32
    关注

    So, assuming you want to render this on the server (which is the simplest to explain), this is fairly simple.

    Give your right sidebar an id so you can reference it with jQuery like $("#the-id-here");

    Using $.get(), you can do an ajax request to your server. You will need to send the data for what element you're clicking on so django knows what results to return. For practice just make sure you can create a simple django view that you can query with $.get, and see if you can return a response. For AJAX, you will most likely want either django.http.HttpResponse or django.http.JsonResponse.

    Once you have your endpoint setup and you've verified that you can access it with AJAX, you need to return some HTML. Create an HTML template in your project. For AJAX requests where I'm not rendering a full page, I like to create a subfolder in my templates directory called components/ or partials/. You don't have to, but it helps to keep things organized.

    For AJAX methods that render a template, I like to use render_to_string. This gives me some freedom about how I want the response to be formatted. For example, if I wanted to return some JSON which includes the HTML as well as some metadata, I could do:

    return JsonResponse({
      "html": render_to_string("my_template.html", {"data": "abc"}),
      "status": "ok"
    })
    

    Back in the javascript, after you make your AJAX call you'll have a success callback function. In the callback you will want to update the html of the container with $("#your-element").html(/* response here */)

    So to summarize

    1. Create a container in the HTML with an ID that you can select iwth jQuery
    2. Create a django view and verify you can do an ajax call to it
    3. Create your template that will be rendered and sent back
    4. Render the template using render_to_string and JsonResponse if you need more control over the response.
    5. In your AJAX success callback, use the response to fill your container with the rendered template.
    评论

报告相同问题?