开发者

Simple jQuery post question (using Django)

sing django and jQuery

I am trying to implement a button that, using the post method, would send an id of a field to be deleted from the db.

feed_list.html

<form id="get_feed_frm">
{% csrf_token %}
{% for news in new_feed %}
<ul class = {{news.pk}}>

    <button id = {{news.pk}}>  Remove</button>
     <script>
        $("#{{news.pk}}").click(function () { 
                $('ul').remove('.{{news.pk}}');
                $.post('/?ajax', { csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), id: '{{news.pk}}'});
                }) </script>
    {{ n开发者_如何学Cews.question }}
    <hr />
</ul>
{% endfor %}
</form>

I can achieve the desired result with this code. However, when I remove the

$('ul').remove('.{{news.pk}}');

line from my script, the function doesn't work, and i cannot explain why it's the case. I would really appreciate your input on this.

-r

EDIT:

Thx Yuji I learned a couple of tricks that will help me better write my code. However I still have the same problem.

I posted below my view code as I must be doing something fundamentally wrong with my view or the way I send the post method

def recent_feed_view(request):

print "Entering View"
new_feed = []
if 'id' in request.POST:
    delete_id = request.POST['id'].strip()
    print "____id____" #just for debugging purpuse
    print delete_id
    n = news.objects.get(pk=delete_id)
    n.discarded = True
    n.save()

new_feed = news.objects.filter(discarded = False)

variables = RequestContext(request, {'new_feed': new_feed})

if 'ajax' in request.POST:
    print "______AJAX_______"

return render_to_response('feed_list.html', variables)  

EVerytime I run the site, The URL correctly links the execution to the correct view, and I get the following message in the command prompt:

[06/Mar/2011 16:59:38] "GET /?csrfmiddlewaretoken=e724dfb883965aaa0edfb6ef521a885c HTTP/1.1" 200 1017

EDIT

Yuji, (thx for introducing me to Chrom dev tool! I am still a newbie and learning a lot thanks to you!)

I followed your advice 2 things happened for me here:

running this code in the Chrome dev tool:

$.ajax({
                type: 'POST',
                url: '/?ajax',
                data: {
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                id:44
                    }
                });

the dev server received a post: The correct entry was discarded from my code, and i had to manually refresh the page to see the changes made

Entering View
____id____
44
[06/Mar/2011 18:20:27] "POST /?ajax HTTP/1.1" 200 1203

Incorporating the above script in my site I would receive:

Entering View
 ____id____
45
[06/Mar/2011 18:29:18] "POST /?ajax HTTP/1.1" 200 968
Entering View
[06/Mar/2011 18:29:18] "GET /?csrfmiddlewaretoken=e724dfb883965aaa0edfb6ef521a885c HTTP/1.1" 200 968

For some reason I am getting a POST and a GET; I used this script:

    <script type="text/javascript">
    $(function() {
        $(".remove-button").click(function() {

            $.ajax({
                type: 'POST',
                url: '/?ajax',
                data: {
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                id:$(this).attr('id')
                    }
                });
        })
    })
       </script>


Since I don't see why removing that line would prevent the $.post line from happening, I'm going to start suggesting fixing some syntax problems that the browser may be having trouble parsing.

You need quotes around the values you're putting in for class name and button id.

Those lines were causing trouble for my syntax highlighter, so who knows...

<ul class = "{{news.pk}}">
    <button id = "{{news.pk}}">  Remove</button>

Also this part is just a suggestion, but instead of embedding a <script> per row, you should do something like adding a class to each button so that you only have to define your jquery action once.

Consider this: <button id = "{{news.pk}}" class="remove-button"> Remove</button>

<script type="text/javascript">
    $(function() {
        $(".remove-button").click(function() {
            $.post('/?ajax', { 
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                id: $(this).attr('id')
                });
        })
    })
</script>

The dev server is thinking it's a GET request -- can you try manually using the $.ajax function? I wonder if a previous version of jQuery got confused with you passing in get params to your POST?

$.ajax({
  type: 'POST',
  url: '/?ajax',
  data: {
       csrfmiddlewaretoken: $(...),
       id: ...
  }
});

PS: This is a place where google chrome dev tools or firebug come in really handy, you can just type away raw jquery commands :)


You can configure jQuery to retrive the token from cookies set by Django and set the correct header to use in every jQuery.ajax and jQuery.post.

(function($){
    if(!$) {
        return;
    }

    var match = document.cookie.match(/csrftoken=(\w+)/);
    var token = match ? match[1] : '';

    $.ajaxSetup({
        headers: { 'X-CSRFToken': token }
    });

})(window.jQuery);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜