Py学习  »  问与答

求教大神指点 django模板怎么写ajax来操作数据库?

jack_czm • 9 年前 • 5440 次点击  

我不会写ajax来POST一个东西给数据库来做删除 收藏的功能。。。求指点啊

模板代码:

<div style="height:45px;"></div>
    {% if merchant_list %}
       {% for merchant in merchant_list %}

    <div class="collect">
        <span class="collect-left"><a href=""><img src="/static/images/home10.png"></a></span>
        <span class="collect-right">
            <h4>{{ merchant.name }}</h4>
            <p>{{ merchant.address }}</p>
            <p>配送时间:<a class="colorred">{{ merchant.service_start_time|date:"H: i" }}-{{ merchant.service_end_time|date:"H: i" }}</a></p>
            <p class="coloryellow fontsize12">{{ merchant.free_start_price }}元起送</p>

            <button class="delete" del_id="{{ merchant.id}}">删除此收藏</button>

jquery代码:

<script type="text/javascript" src="/static/js/jquery.js"></script>
<script>
$(document).ready(function(){
    $('.delete').click(function(){
     if(confirm("是否删除此收藏"))
    $(this).parents(".collect").remove();
        var del_id=$(this).val()
        $.post('/wechat/my/del_favorite',{'del':del_id })

    });
});
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/733
 
5440 次点击  
文章 [ 2 ]  |  最新文章 9 年前
Py站长
Reply   •   1 楼
Py站长    9 年前

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

Put dataType: "json" in the jquery call. The resp will be a javascript object.

$.ajax({
    url: "/ajax/",
    type: "POST",
    data: name,
    cache:false,
    dataType: "json",
    success: function(resp){
        alert ("resp: "+resp.name);
    }
});

In Django, you must return a json-serialized dictionnary containing the data. The content_type must be application/json. In this case, the locals trick is not recommended because it is possible that some local variables can not be serialized in json. This wil raise an exception. Please also note that is_ajax is a function and must be called. In your case it will always be true. I would also test request.method rather than request.POST

import json
def lat_ajax(request):

    if request.method == 'POST' and request.is_ajax():
        name = request.POST.get('name')
        return HttpResponse(json.dumps({'name': name}), content_type="application/json")
    else :
        return render_to_response('ajax_test.html', locals())

UPDATE : As mentioned by Jurudocs, csrf_token can also be a cause I would ecommend to read : https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

http://stackoverflow.com/questions/14642130/how-to-response-ajax-request-in-django

fanglq04
Reply   •   2 楼
fanglq04    9 年前

同问