ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

django框架之模型层-Ajax

2022-09-08 00:01:56  阅读:264  来源: 互联网

标签:框架 list request json publish django Ajax book POST


目录

Ajax基本操作

1.Ajax:js自带的功能(学习的是jQuery封装之后的版本)
2.Ajax与form表单的区别
Ajax:异步提交 局部刷新
form表单:同步提交 涉及整个页面
3.基础语法:

            $.ajax({
                url:'',           # 控制数据提交的地址 相当于form表单中的action
                type:'post',      # 控制请求方式(默认是get请求) 相当于form表单中的method
                data:{},          # 组织提交的数据
                success:function (args) {     # success异步回调函数(函数返回什么就传入什么)
                    $('#d3').val(args)
                }
            })
4.实操
html操作:
    <body>
        <input type="text" id="d1">+<input type="text" id="d2">=<input type="text" id="d3">
        <input type="button" value="合并" id="btn">
    </body>
        <script>
            $('#btn').click(function () {
                $.ajax({
                    url:'',
                    type:'post',
                    data:{'i1':$('#d1').val(),'i2':$('#d2').val()},
                    success:function (args) {
                        $('#d3').val(args)
                    }
                })
            })
        </script>
views.py操作:
    def ajax(request):
    if request.method == 'POST':
        i1 = request.POST.get('i1')
        i2 = request.POST.get('i2')
        i = i1+i2
        return HttpResponse(i)
    return render(request, 'a_ajax.html', locals())

数据编码格式

1.数据编码格式
  1.1格式一:urlencoded
        数据格式:name=lili&age=18
        django后端统一将数据放到request.POST中  
  1.2.格式二:formdata
          数据格式:无法查看(二进制格式)
          django后端自动将文件数据处理到request.FILES 普通数据request.POST
  1.3.格式三:application/json
		 数据格式:json(form表单无法操作)
          django后端不会处理 在request.body中存储(bytes类型)  所有的数据开始都会放在body中
          语法注意事项:data:JSON.stringify({'name':'lili'})    编码
                       contentType:'application/json'
 2.实操
   Html操作:
     $('#btn').click(function () {
            $.ajax({
                url:'',
                type:'post',
                data:JSON.stringify({'name':'lili'}),
                contentType:'application/json',
                success:function (args) {
                }
            })
        })
 views操作:
  def ajax(request):
    if request.is_ajax():
        if request.method == 'POST'
            json_bytes = request.body       # b'{"name":"lili"}'
            import json
            json_dict = json.loads(json_bytes)
            print(json_dict, type(json_bytes))   # {'name': 'lili'} <class 'bytes'>
    return render(request, 'a_ajax.html', locals())

Ajax携带文件数据

        $('#btn').click(function(){
            let formData = new FormData();   //1.产生内置对象
            formData.append('username',$('#d1').val())     //2.添加普通数据
            formData.append('file', $('#d2')[0].file[0])   //3.添加文件数据
            //4.发送ajax请求
            $.ajax({
                url:'',
                type:'post',
                data:formData,
                contentType:false,    //不使用任何编码
                processData:false,    //不处理任何数据对象
                success:function (args) {
                }
                }
            })
            def ajax(request):

                if request.is_ajax():
                    if request.method == 'POST':
                        print(request.POST)
                        print(request.FILES)
    		return render(request, 'a_ajax.html')

Ajax回调函数参数问题

1.回调函数:
  后端与ajax交互 通常情况下返回json格式数据
  前端针对HttpResponse和JsonResponse返回的json格式数据处理策略不同
  HttpResponse不会自动反序列化 
    1.需要我们自己操作json.loads(json_bytes)
    2.也可以添加固定参数:dataType:'JSON'
  JsonResponse会自动反序列化 

sweetalter介绍

1.插件操作:可以设置二次确认的动态框样式 可以从bootstrap中查找样式

django自带的序列化组件

def get_book(request):
    book_query = models.Book.objects.all()
    # 将数据全部构造成json格式 {'pk':1,'title':'书'}  操作麻烦
    # book_list = []
    # for book_obj in book_query:
    #     temp_dict = {}
    #     temp_dict['pk'] = book_obj.pk
    #     temp_dict['title'] = book_obj.title
    #     temp_dict['price'] = book_obj.price
    #     book_list.append(temp_dict)
    from django.core import serializers   # 使用这种方式
    # 调用该模块下的方法,第一个参数是以什么样的方式序列化数据
    res = serializers.serialize('json', book_query)
    return HttpResponse(res)
    # return HttpResponse(book_list)       # {'pk': 1, 'title': '云边有个小卖部'}

图书管理系统

1.页面展示代码:

def book(request):
    book_list = models.Book.objects.select_related('book_publish').order_by('pk')
    return render(request, 'book.html', locals())
            <h1 class="text-center">数据添加页面</h1>
            <form action="" method="post">
                <p class="form-control">书名:
                    <input type="text" name="title"></p>
                <p class="form-control">价格:
                    <input type="text" name="price"></p>
                <p class="form-control">日期:
                    <input type="date" name="pub_date" ></p>
                <select class="form-control" multiple name="author_list" id="" >作者:
                      {% for author_obj in author_list %}
                          <option value="{{ author_obj.pk }}">{{ author_obj.name }}
                      {% endfor %}
                 </select>
                        <select class="form-control" name="book_publish_id" id="">出版社:
                    {% for publish_obj in publish_list %}
                        <option value="{{ publish_obj.pk }}">{{ publish_obj.name }}
                    {% endfor %}
                </select>
                <p><input type="submit" class="btn btn-primary" value="添加"></p>
            </form>


2.数据添加代码

def book_add(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        price = request.POST.get('price')
        pub_date = request.POST.get('pub_date')
        book_publish_id = request.POST.get('book_publish_id')
        author_list = request.POST.getlist('author_list')
        # 添加数据
        book_obj = models.Book.objects.create(
            title=title,
            price=price,
            pub_date=pub_date,
            book_publish_id=book_publish_id
        )
        print(book_obj)
        book_obj.book_author.add(*author_list)   # *在实参中将列表数据打撒 以位置参数传入
        # 跳转到书籍展示页
        book_target = reverse('app01_book_views')
        return redirect(book_target)
    publish_list = models.Publish.objects.all()
    author_list = models.Author.objects.all()
    return render(request, 'book_add.html', locals())

3.编辑数据代码

def book_update(request, update_id):
    # 获取用户编辑对象
    update_obj = models.Book.objects.filter(pk=update_id).first()
    if request.method == 'POST':
        title = request.POST.get('title')
        price = request.POST.get('price')
        pub_date = request.POST.get('pub_date')
        book_publish_id = request.POST.get('book_publish_id')
        author_list = request.POST.getlist('author_list')
        # 修改数据
        models.Book.objects.filter(pk=update_id).update(
            title=title,
            price=price,
            pub_date=pub_date,
            book_publish_id=book_publish_id
        )
        print(update_obj)
        update_obj.book_author.set(author_list)
        # 跳转到书籍展示页
        book_target = reverse('app01_book_views')
        return redirect(book_target)
    publish_list = models.Publish.objects.all()
    author_list = models.Author.objects.all()
    return render(request, 'book_update.html', locals())

4.删除数据

def book_del(request, del_id):
    models.Book.objects.filter(pk=del_id).delete()
    return redirect('app01_book_views')

标签:框架,list,request,json,publish,django,Ajax,book,POST
来源: https://www.cnblogs.com/040714zq/p/16667230.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有