社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  问与答

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

jack_czm • 10 年前 • 6049 次点击  

我不会写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
 
6049 次点击  
文章 [ 2 ]  |  最新文章 10 年前
Py站长
Reply   •   1 楼
Py站长    10 年前

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    10 年前

同问