温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Django中使用Ajax

发布时间:2021-03-30 16:54:59 来源:亿速云 阅读:730 作者:Leah 栏目:web开发

这篇文章给大家介绍如何在Django中使用Ajax,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

一、ajax发送简单数据类型:

html代码:在这里我们仅发送一个简单的字符串

views.py

 #coding:utf8
 from django.shortcuts import render,HttpResponse,render_to_response
 def Ajax(request):
   if request.method=='POST':
     print request.POST
     return HttpResponse('执行成功')
   else:
     return render_to_response('app03/ajax.html')

ajax.html

<!DOCTYPE html>
 <html>
 <head>
 <meta charset="UTF-8">
 <title>Ajax</title>
 </head>
 <body>
   <input id='name' type='text' />
   <input type='button' value='点击执行Ajax请求' onclick='DoAjax()' />
   <script src='/static/jquery/jquery-3.2.1.js'></script>
   <script type='text/javascript'>
   function DoAjax(){
     var temp = $('#name').val();
     $.ajax({
       url:'app03/ajax/',
       type:'POST',
       data:{data:temp},
       success:function(arg){
         console.log(arg);
       },
       error:function(){
         console.log('failed')
       }
     });
   }
   </script>
 </html>

运行,结果:

如何在Django中使用Ajax

如何在Django中使用Ajax

二、ajax发送复杂的数据类型:

html代码:在这里仅发送一个列表中包含字典数据类型

由于发送的数据类型为列表 字典的格式,我们提前要把它们转换成字符串形式,否则后台程序接收到的数据格式不是我们想要的类型,所以在ajax传输数据时需要JSON

<!DOCTYPE html>
 <html>
 <head>
 <meta charset="UTF-">
 <title>Ajax</title>
 </head>
 <body>
   <input id='name' type='text' />
   <input type='button' value='点击执行Ajax请求' onclick='DoAjax()' />
   <script src='/static/jquery/jquery-3.2.1.js'></script>
   <script type='text/javascript'>
   function DoAjax(){
     var temp = $('#name').val();
     $.ajax({
       url:'app03/ajax/',
       type:'POST',
       data:{data:temp},
       success:function(arg){
         var obj=jQuery.parseJSON(arg);
         console.log(obj.status);
         console.log(obj.msg);
         console.log(obj.data);
         $('#name').val(obj.msg);
       },
       error:function(){
         console.log('failed')
       }
     });
   }
   </script>
 </html>

views.py

 #coding:utf
 from django.shortcuts import render,HttpResponse,render_to_response
 import json
 # Create your views here.
 def Ajax(request):
   if request.method=='POST':
     print request.POST
     data = {'status':,'msg':'请求成功','data':['','','']}
     return HttpResponse(json.dumps(data))
   else:
     return render_to_response('app/ajax.html')

打印数据样式:

如何在Django中使用Ajax

如何在Django中使用Ajax

关于如何在Django中使用Ajax就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI