Django+Ajax+jQuery實現(xiàn)網頁動態(tài)更新的實例
views.py中的修改
增加相應的請求處理函數(shù):
def getdevjson(request):
print 'get here'
if ('key' in request.GET):
searchkey = request.GET.get('key')
return JsonResponse(search(searchkey))
else:
return HttpResponse('Sorry!')
返回字符串中,既可以使用from django.http import JsonResponse,也可以使用HttpResponse(json.dumps(res))
前端網頁修改
<script type="text/javascript">
window.jQuery || document.write("<script src='../static/js/jquery.min.js'>" + "<" + "/script>");
</script>
<script type="text/javascript">
$(function() {
var submit_form = function(e) {
$.ajax({
type : "GET",
url : "/getdevjson?"+Math.random(),
data : {
key: $('#searchContent').val()
},
dataType : "text",
success : function(res){
$('#searchContent').focus().select();
//console.log(res);
update(res);
},
error : function() {
alert("處理異常返回!");}
});
return false;
};
$('#calculate').bind('click', submit_form);
$('input[type=text]').bind('keydown', function(e) {
if (e.keyCode == 13) {
submit_form(e);
}
});
$('#searchContent').focus();
});
</script>
<div class="divRight" id="divright1"> <div class="divRight" style="height:70px; width:370px;"> <label id="lblSearch" class="cssLabelSearch">請輸入查詢key:</label> <input id="searchContent" type="text" size="40"></input> <input id="calculate" type="button" value="確定" ></input> </div> <br> <label id="lbl1" class="cssLabelClient">節(jié)點信息</label> <Textarea id="ClientInfoArea" readonly class="txtClientInfo"></Textarea> </div>
#calculate是一個按鈕,點擊動作綁定了提交函數(shù)submit_form,ajax的請求參數(shù)中,data中包含了查詢參數(shù),success是請求成功后的動作,注意返回的res需要進行json解析才可以正確使用:root = JSON.parse(jsondata);update(res)是一個更新網頁內容的函數(shù)
路由配置修改
urls.py中修改如下:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^getdevjson$','dev.views.getdevjson',name='getdevjson'),
url(r'^','dev.views.index',name='index'),
url(r'^admin/', include(admin.site.urls)),
)
需要注意的是為了避免路由被覆蓋,將index的路由配置盡量放置在最后一行。
以上這篇Django+Ajax+jQuery實現(xiàn)網頁動態(tài)更新的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
matlab灰度圖像調整及imadjust函數(shù)的用法詳解
這篇文章主要介紹了matlab圖像灰度調整及imadjust函數(shù)的用法詳解,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02
Python協(xié)程異步爬取數(shù)據(asyncio+aiohttp)實例
這篇文章主要為大家介紹了Python協(xié)程異步爬取數(shù)據(asyncio+aiohttp)實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
對python創(chuàng)建及引用動態(tài)變量名的示例講解
今天小編就為大家分享一篇對python創(chuàng)建及引用動態(tài)變量名的示例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11

