Heim  >  Artikel  >  Backend-Entwicklung  >  Verwendung von Django Ajax

Verwendung von Django Ajax

巴扎黑
巴扎黑Original
2017-06-23 14:49:041739Durchsuche

Einführung:

AJAX = Asynchrones JavaScript und XML (Asynchrones JavaScript und XML).

AJAX ist keine neue Programmiersprache, sondern eine neue Art, bestehende Standards zu nutzen.

AJAX ist die Kunst, Daten mit einem Server auszutauschen und Teile einer Webseite zu aktualisieren, ohne die gesamte Seite neu zu laden.

Ajax

Wenn wir eine Operation auf einer Webseite anfordern, tun wir das oft nicht muss die Seite aktualisieren. Die Technologie zum Erreichen dieser Funktion erfordert Ajax!

Ajax in jQuery kann die Funktion des Anforderns oder Sendens von Daten im Hintergrund realisieren, ohne die Seite zu aktualisieren. Jetzt verwende ich es, um Ajax in Django auszuführen. Je höher die Version, desto besser.

1. Ajax sendet einfache Datentypen:

HTML-Code: Hier senden wir nur einen einfachen String

views.py

 1 #coding:utf8 2 from django.shortcuts import render,HttpResponse,render_to_response 3  4 def Ajax(request): 5     if request.method=='POST': 6         print request.POST 7  8         return HttpResponse('执行成功') 9     else:10         return render_to_response('app03/ajax.html')

ajax.html

 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Ajax</title> 6 </head> 7 <body> 8     <input id=&#39;name&#39; type=&#39;text&#39; /> 9     <input type=&#39;button&#39; value=&#39;点击执行Ajax请求&#39; onclick=&#39;DoAjax()&#39; />10 11     <script src=&#39;/static/jquery/jquery-3.2.1.js&#39;></script>12     <script type=&#39;text/javascript&#39;>13      function  DoAjax(){14          var temp = $('#name').val();15          $.ajax({16              url:'app03/ajax/',17              type:'POST',18              data:{data:temp},19              success:function(arg){20                  console.log(arg);21              },22              error:function(){23                  console.log('failed')24              }25          });26      }27     </script>28 </html>

Ausführen, Ergebnis:


2. Ajax sendet komplexe Datentypen:

HTML-Code: Hier wird nur eine Liste mit Wörterbuchdatentypen gesendet

Da der gesendete Datentyp im Format eines Listenwörterbuchs vorliegt, müssen wir ihn vorher in eine Zeichenfolgenform konvertieren, andernfalls wird das Datenformat empfangen von Das Hintergrundprogramm ist nicht der Typ, den wir wollen, also JSON

 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Ajax</title> 6 </head> 7 <body> 8     <input id=&#39;name&#39; type=&#39;text&#39; /> 9     <input type=&#39;button&#39; value=&#39;点击执行Ajax请求&#39; onclick=&#39;DoAjax()&#39; />10 11     <script src=&#39;/static/jquery/jquery-3.2.1.js&#39;></script>12     <script type=&#39;text/javascript&#39;>13      function  DoAjax(){14          var temp = $('#name').val();15          $.ajax({16              url:'app03/ajax/',17              type:'POST',18              data:{data:temp},19              success:function(arg){20                  var  obj=jQuery.parseJSON(arg);21                  console.log(obj.status);22                  console.log(obj.msg);23                  console.log(obj.data);24                  $('#name').val(obj.msg);25              },26              error:function(){27                  console.log('failed')28              }29          });30      }31     </script>32 </html>

views.py

 1 #coding:utf8 2 from django.shortcuts import render,HttpResponse,render_to_response 3 import json 4  5 # Create your views here. 6 def Ajax(request): 7     if request.method=='POST': 8         print request.POST 9         data  = {'status':0,'msg':'请求成功','data':['11','22','33']}10         return HttpResponse(json.dumps(data))11         12     else:13         return render_to_response('app03/ajax.html')

Datenstil drucken:


jQuery Ajax-Methodenliste

 1 jQuery.get(...) 2                 所有参数: 3                      url: 待载入页面的URL地址 4                     data: 待发送 Key/value 参数。 5                  success: 载入成功时回调函数。 6                 dataType: 返回内容格式,xml, json,  script, text, html 7   8   9             jQuery.post(...)10                 所有参数:11                      url: 待载入页面的URL地址12                     data: 待发送 Key/value 参数13                  success: 载入成功时回调函数14                 dataType: 返回内容格式,xml, json,  script, text, html15  16  17             jQuery.getJSON(...)18                 所有参数:19                      url: 待载入页面的URL地址20                     data: 待发送 Key/value 参数。21                  success: 载入成功时回调函数。22  23  24             jQuery.getScript(...)25                 所有参数:26                      url: 待载入页面的URL地址27                     data: 待发送 Key/value 参数。28                  success: 载入成功时回调函数。29  30  31             jQuery.ajax(...)32  33                 部分参数:34  35                         url:请求地址36                        type:请求方式,GET、POST(1.9.0之后用method)37                     headers:请求头38                        data:要发送的数据39                 contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")40                       async:是否异步41                     timeout:设置请求超时时间(毫秒)42  43                  beforeSend:发送请求前执行的函数(全局)44                    complete:完成之后执行的回调函数(全局)45                     success:成功之后执行的回调函数(全局)46                       error:失败之后执行的回调函数(全局)47                  48  49                     accepts:通过请求头发送给服务器,告诉服务器当前客户端课接受的数据类型50                    dataType:将服务器端返回的数据转换成指定类型51                                    "xml": 将服务器端返回的内容转换成xml格式52                                   "text": 将服务器端返回的内容转换成普通文本格式53                                   "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。54                                 "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式55                                   "json": 将服务器端返回的内容转换成相应的JavaScript对象56                                  "jsonp": JSONP 格式57                                           使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数58  59                                   如果不指定,jQuery 将自动根据HTTP包MIME信息返回相应类型(an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string60  61                  converters: 转换器,将服务器端的内容根据指定的dataType转换类型,并传值给success回调函数62                          $.ajax({63                               accepts: {64                                 mycustomtype: 'application/x-some-custom-type'65                               },66                                67                               // Expect a `mycustomtype` back from server68                               dataType: 'mycustomtype'69  70                               // Instructions for how to deserialize a `mycustomtype`71                               converters: {72                                 'text mycustomtype': function(result) {73                                   // Do Stuff74                                   return newresult;75                                 }76                               },77                             });

Datei-Upload implementieren:

views.py

 1 from django.shortcuts import render,HttpResponse,render_to_response 2 import json,os,uuid 3  4 def Upload(request): 5     if request.method=='POST': 6         id = str(uuid.uuid4()) 7         ret = {'status':True,'data':None,'message':None} 8         obj = request.FILES.get('k3') 9         10         file_path = os.path.join('static',id+obj.name)11         f = open(obj.name,'wb')12         for line in obj.chunks():13             f.write(line)14         f.close()15         ret['data'] = file_path16         return HttpResponse(json.dumps(ret))17     else:18         return render_to_response('appajax/put_file.html')

put_file.html

 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>上传文件</title> 6     <style> 7     .log{ 8                display: inline-block; 9                 padding:5px 10px;10                 background-color:coral;11                 color: white;12             }13     </style>14 </head>15 <body>16     <iframe style="display:none" id="ifrname1" name="ifra1"></iframe>17     <form id="fm1" action="/appajax/put_file.html" method="post" enctype="multipart/form-data" target="ifra1">18         <input type="file" name="k3" onchange="UploadFile();"/>19     </form>20     <h3>预览</h3>21     <div id="preview"></div>22     23     <script src="/static/jquery/jquery-3.2.1.js?1.1.10"></script>24     <script type="text/javascript">25         function UploadFile(){26             document.getElementById('iframe1').onload = ReloadIfrname();27             document.getElementById('fm1').submit();28         };29         function ReloadIfrname(){30             var content = this.contentWindow.document.body.innerHTML;31             var obj = JSON.parse(content);32             var tag = document.createElement('img');33             tar.src = obj.data;34             $('#preview').empty().append(tag);35         };36     </script>37 </body>38 </html>

Das obige ist der detaillierte Inhalt vonVerwendung von Django Ajax. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn