簡(jiǎn)介:
AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML)。
AJAX 不是新的編程語(yǔ)言,而是一種使用現(xiàn)有標(biāo)準(zhǔn)的新方法。
AJAX 是與服務(wù)器交換數(shù)據(jù)并更新部分網(wǎng)頁(yè)的藝術(shù),在不重新加載整個(gè)頁(yè)面的情況下。
Ajax
很多時(shí)候,我們?cè)诰W(wǎng)頁(yè)上請(qǐng)求操作時(shí),不需要刷新頁(yè)面。實(shí)現(xiàn)這種功能的技術(shù)就要Ajax!
jQuery中的ajax就可以實(shí)現(xiàn)不刷新頁(yè)面就能向后臺(tái)請(qǐng)求或提交數(shù)據(jù)的功能,現(xiàn)用它來(lái)做django中的ajax,所以先把jquey下載下來(lái),版本越高越好。
一、ajax發(fā)送簡(jiǎn)單數(shù)據(jù)類(lèi)型:
html代碼:在這里我們僅發(fā)送一個(gè)簡(jiǎn)單的字符串
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('執(zhí)行成功') 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='點(diǎn)擊執(zhí)行Ajax請(qǐng)求' 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>
運(yùn)行,結(jié)果:
二、ajax發(fā)送復(fù)雜的數(shù)據(jù)類(lèi)型:
html代碼:在這里僅發(fā)送一個(gè)列表中包含字典數(shù)據(jù)類(lèi)型
由于發(fā)送的數(shù)據(jù)類(lèi)型為列表 字典的格式,我們提前要把它們轉(zhuǎn)換成字符串形式,否則后臺(tái)程序接收到的數(shù)據(jù)格式不是我們想要的類(lèi)型,所以在ajax傳輸數(shù)據(jù)時(shí)需要JSON
<!DOCTYPE html> <html> <head> <meta charset="UTF-"> <title>Ajax</title> </head> <body> <input id='name' type='text' /> <input type='button' value='點(diǎn)擊執(zhí)行Ajax請(qǐng)求' 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':'請(qǐng)求成功','data':['','','']} return HttpResponse(json.dumps(data)) else: return render_to_response('app/ajax.html')
打印數(shù)據(jù)樣式:
以上所述是小編給大家介紹的Django Ajax的使用教程,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com