首页 > 其他分享 >django 09 ajax

django 09 ajax

时间:2022-12-20 17:55:05浏览次数:46  
标签:function args return 09 request django ajax data

Ajax

#  ajax:异步提交,局部刷新
Async 异步 // 1.ajax有许多版本,此次学习的位jQuery版本(无关版本,本质相同) // 2.基本语法 $.ajax({ url:' ', // 后端地址 三种填写方式 与form标签的action一致 type:'post', // 请求方式 默认也是get data:{'v1':v1Val, 'v2':v2Val}, // 发送的数据 success:function (args) { // 后端返回结果之后自动触发 args接收后端返回的数据 $('#d3').val(args) } })


# 实例展示
# 1.路由层:
from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('ab_ajax/',views.ab_ajax_func)
]
# 2.配置文件
# 3.视图层
from django.shortcuts import render,HttpResponse,redirect

def ab_ajax_func(request):
    if request.method == 'POST':
        print(request.POST)
        # return HttpResponse("ajax")
        # return render(request,'abAjaxPage.html')
        # return redirect('https://www.baidu.com')
        v1 = request.POST.get('v1')
        v2 = request.POST.get('v2')
        res = int(v1) + int(v2)
        return HttpResponse(res)
    return render(request,'abAjaxPage.html')
# 4.模板层abAjaxPage.html文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.2/jquery.js"></script>
</head>
<body>
<input type="text" id="d1"> + <input type="text" id="d2"> = <input type="text" id="d3">
{#<button id="subBtn">发送ajax请求</button>#}
<script>
    // 2.给按钮绑定点击事件
    {#$('#subBtn').click(function(){#}
    $('#d2').blur(function(){
       // 1.获取两个框里的数据
       let v1Val = $('#d1').val();
       let v2Val = $('#d2').val();
       // 3.发送ajax请求
       $.ajax({
           'url':'',
           'type':'post',
           'data':{'v1':v1Val, 'v2':v2Val },
           success:function (args) {
              $('#d3').val(args)
           }
       })
   })
</script>
</body>
</html>

Content-Type

 

# 1.urlencoded
     """ form表单默认的编码格式,也是ajax的默认编码格式"""
     - 数据格式   aaa=xxx&bbb=yyy 
     - django后端会自动处理到request.POST中

# 2.formdata
     - django后端针对普通的键值对也会处理到request.POST中
     - 针对于文件则会处理到request.FILES中


"""form表单只支持上面两种,而ajax还支持其他"""

# 3.application/json
     - django针对json格式数据需要后端从request.body中获取并处理
         """
         print(request.body)
         import json
         res = json.loads(request.body)
         """
     - 前端ajax代码
         <script>
         $('#d1').click(function () {
             $.ajax({
                 url:'',
                 type:'post',
                 data:JSON.stringify({'name':'jason','age':18}),  // 千万不要骗人家
                 contentType:'application/json',
                 success:function (args) {
                     alert(args)
                 }
             })
          })
          </script>

ajax携带文件数据

<input type="text" id="d1">
<input type="text" id="d2">
<button id="d3">携带文件数据</button>

<script>
    $('d3').click(function (){
        // 1.先产生一个formdata对象
        let myFormDataObj = new FormData()
        // 2.往对象中添加普通数据
        myFormDataObj.append('name','jason');
        myFormDataObj.append('age',18);
        // 3.往该对象中添加文件数据
        myFormDataObj.append('file',$('#d2')[0].files[0])
        // 4.发送ajax请求
        $.ajax({
            url:'',
            type:'',  
            data:myFormDataObj,
            // ajax发送文件固定的两个配置
            contentType:false,
            processData:false,
            success:function (args){
                alert(args)
            }
        })
    })

</script>

回调函数args接收到的响应数据

# 1.后端request.is_ajax()
     request.is_ajax()      # 用于判断当前请求是不是ajax发出的
   - 访问页面结果为false,点击按钮结果为true
     
       视图层:
       def ab_ajax_func(request):
           print(request.is_ajax())
           return render(request,'abAjaxPage.html')
       前端:
       <button id="d1">发送ajax请求</button>
       <script>
       $('#d1').click(function () {
           $.ajax({
                url:'',
                type:'post',
                data:{'name':'jason'},
                success:function (args) {
                    console.log(args)
                }
           })
        })
        </script>
 

# 2.后端返回的三板斧都会被args接收,并且不会影响整个浏览器页面

# 3.选择ajax进行前后端交互时,后端一般返回的都是字典数据
     - 将其转为前端能识别的json格式对象
  - 方式一:
       后端:
         def ab_ajax_func(request):
             if request.method == 'POST':
                 # code是自定义的状态码
                 user_dict = {'code':10000,'username':'喜羊羊','hobby':'吃草'}
                 import json
                 user_data = json.dumps(user_dict)
                 # 返回给前端是一个js格式字符串类型,容易出错,不好用可以把其封装为前端的自定义对象类型
                 return HttpResponse(user_data)
             return render(request,'abAjaxPage.html')

       前端:
         <button id="d1">发送ajax请求</button>
         <script>
         $('#d1').click(function () {
            $.ajax({
                url:'',
                type:'post',
                data:{'name':'jason'},
                success:function (args) {
                    let userObj = JSON.parse(args);
                    console.log(userObj);
                    console.log(typeof userObj);
                    console.log(userObj.username)
                }
             })
          })

  - 方式二:
       后端:
          from django.http import JsonResponse
          def ab_ajax_func(request):
              if request.method == 'POST':
                  # code是自定义的状态码
                  user_dict = {'code':10000,'username':'喜羊羊','hobby':'吃草'}
                  return JsonResponse(user_dict)
              return render(request,'abAjaxPage.html')

       前端:
         <button id="d1">发送ajax请求</button>
         <script>
             $('#d1').click(function () {
                 $.ajax({
                     url:'',
                     type:'post',
                     data:{'name':'jason'},
                     success:function (args) {
                         console.log(args);
                         console.log(typeof args);
                         console.log(args.username)
                     }
                  })
               })
               </script>

 

标签:function,args,return,09,request,django,ajax,data
From: https://www.cnblogs.com/juzijunjun/p/16993238.html

相关文章

  • ajax补充,多对多三种创建方式,Django内置序列化,orm批量操作数据,自定义分页,form组件
    目录今日内容概要今日内容详细ajax补充说明多对多三种创建方式django内置序列化组件(drf前身)批量操作数据分页器思路自定义分页器的使用form组件今日内容概要ajax补充......
  • django组件:批量操作、分页器思路及自定义分页器
    目录django内置序列化组件(drf前身)批量操作数据分页器自定义分页器的使用form组件django内置序列化组件(drf前身)urls.py:#序列化组件path('ab_ser/',views.ab_ser),vi......
  • django取消debug获取不到静态资源
    1.debug=True状态下我们可以看到mysql查询语句的打印,如何不显示这些打印呢2.setting修改一下内容DEBUG=FalseifDEBUGisTrue:STATICFILES_DIRS=(os.path.j......
  • django基本流程
    创建项目django-adminstartprojectwebcdwebpythonmanage.pystartappweblist生成迁移文件pythonmanage.pymakemigrations生成迁移数据pythonmanage.py......
  • 聚合查询、分组查询、ORM中如何给表再次添加新的字段、F与Q查询、ORM查询优化、ORM事
    今日内容聚合查询在ORM中支持单独使用聚合函数,需要使用aggregate方法。聚合函数:Max最大、Min最小、Sum总和、Avg平均、count统计fromdjango.db.modelsimportMax,......
  • django组件使用
    django内置序列化组件(drf前身)'''前后端分离的项目视图函数只需要返回json格式的数据即可'''fromapp01importmodelsfromdjango.httpimportJsonResponsedefa......
  • django模型层之models入门篇(filed options)
    一、新建一个django项目,注册两个app分别为tournament、comment,其中models的代码分别为:#tournament/models.pyfromdjango.dbimportmodelsclassClub(models.Model......
  • HDU5091 Beam Cannon
    \(HDU5091\)\(Beam\)\(Cannon\)一、题目大意有\(n\)个点(\(n<=10000\)),点的坐标绝对值不超过\(20000\),然后问你用一个\(w*h(1<=w,h<=40000)\)的矩形,矩形的边平行于坐标......
  • django框架(七)
    (3)Q查询进阶操作研究查询条件的左边是什么?字段名还是变量名?models.Book.objects.filter(pk=1)发现是变量名如果想让左边不是变量名而是字段名,则需要用到Q查询Q:还可......
  • Ajax
    Ajax异步提交局部刷新全称:AJAX(AsynchronousJavascriptAndXML)中文名为:异步javascript和XML通过JavaScript来操作发送请求到服务端XML:数据交互使用XML,现在主流使用J......