[Django学习]Ajax访问静态页面

Web开发中常用的一种开发方式是:通过Ajax进行系统的交互,采用Ajax进行交互的时候,更多的时候传输的是JSON格式的数据。

所以开发中我们需要将数据格式转化成JSON,请参见:https://www.cnblogs.com/coser/archive/2011/12/14/2287739.html

但是由于Django已经帮我们封装了一些东西,所以我们可以写成格式:

'''
Ajax测试
用ajax需要关闭csrf
'''
@csrf_exempt
def ajax(request):
    booklist = BookInfo.books.all().values()
    return JsonResponse(list(booklist), safe=False)

@csrf_exempt
def ajax2(request):
    booklist = BookInfo.books.all()
    list = []
    for bookInfo in booklist:
        list.append({'id':bookInfo.id, 'bcomment':bookInfo.bcomment, 'btitle':bookInfo.btitle,
                     'bpub_date':bookInfo.bpub_date, 'isDelete':bookInfo.isDelete, 'bread':bookInfo.bread})
    return JsonResponse(list, safe=False)

以上两种方式转成JSON均可以,配置完URL,就可以通过Ajax进行访问。有两点需要注意:1.要关闭csrf  2.Response的安全模式要设置成False。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/booktest/js/jquery-1.12.4.min.js"></script>
    <script type="application/javascript">
        $(function(){
            $.ajax({
                url:'/booktest/ajax/',
                type:'post',
                datatype:'json',
                success:function (data) {
                    for(var i=0; i < data.length; i++){
                        alert(data[i].btitle)
                    }
                },
                error:function(){
                    alert('失败');
                }
            });
        });
    </script>
</head>
<body>

</body>
</html>
原文地址:https://www.cnblogs.com/DarrenChan/p/7904198.html