开发者

How to implement ajax using Django and Jquery?

开发者 https://www.devze.com 2023-03-09 05:41 出处:网络
urls.py: .... (r\'^blog/post/$\', post), .... View code: def post(request): if request.method == \'POST\': post, created = Post.objects.get_or_create(

urls.py:

....
(r'^blog/post/$', post),
....

View code:

def post(request):

    if request.method == 'POST':



      post, created = Post.objects.get_or_create(
          title=request.POST.get("title"),
          text=request.POST.get("text"),

      )

    post_titles = [post.title for post in Post.objects.all()]
    return render_to_response("index.html", {"post_titles":post_titles})

Templates:

<script type="text/javascript" charset="utf-8">
            $(document).ready(function() {

                $("input#submit").click(function() {


                var title = $("#title").val();
                    var text = $("#text").val();    

                    var data = {"title":title,"text":text};

                    $.post("/blog/post/", data, function(data){
                        alert("Data Loaded: " + data);
           开发者_Go百科         });
                });


            });
        </script>
        .........
        <div id="postbox">
      <form method="post" action="">
            <p>Enter Title</p><input type="text" name="title" id="title">
            <p>Enter Text</p><input type="text" name="text" id="text">
            <input type="submit" id="submit">
          </form>
        </div>

I want the post to get added into the database without page refresh and also "title" and "text" get appended somewhere in the html page. Please tell me what I am doing wrong. Thanks.


I have had very good luck using Dajax/Dajaxice, which is well-documented, has several working demos (with code) of examples of integrating Django with ajax through jQuery. I'd give a longer answer if you gave debugging output (e.g., does the alert box come up; what's the text in it). My guess is your view function with 'render_to_response' of 'index.html' is not what you want with ajax. Typically you just want to send some sort of structured data (usually json or xml) with your ajax from the server (to a previously rendered page).

0

精彩评论

暂无评论...
验证码 换一张
取 消