当前位置: 移动技术网 > IT编程>脚本编程>Ajax > Django Ajax的使用教程

Django Ajax的使用教程

2017年12月08日  | 移动技术网IT编程  | 我要评论
简介: ajax = asynchronous javascript and xml(异步的 javascript 和 xml)。 ajax 不是新的编程语言,而是一种

简介:

ajax = asynchronous javascript and xml(异步的 javascript 和 xml)。

ajax 不是新的编程语言,而是一种使用现有标准的新方法。

ajax 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。

ajax

  很多时候,我们在网页上请求操作时,不需要刷新页面。实现这种功能的技术就要ajax!

jquery中的ajax就可以实现不刷新页面就能向后台请求或提交数据的功能,现用它来做django中的ajax,所以先把jquey下载下来,版本越高越好。

一、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>

运行,结果:

二、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的使用教程,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网