您好,登錄后才能下訂單哦!
這篇文章給大家介紹如何在Django中使用Ajax,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
一、ajax發(fā)送簡(jiǎn)單數(shù)據(jù)類型:
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ù)類型:
html代碼:在這里僅發(fā)送一個(gè)列表中包含字典數(shù)據(jù)類型
由于發(fā)送的數(shù)據(jù)類型為列表 字典的格式,我們提前要把它們轉(zhuǎn)換成字符串形式,否則后臺(tái)程序接收到的數(shù)據(jù)格式不是我們想要的類型,所以在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ù)樣式:
關(guān)于如何在Django中使用Ajax就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。