Django+Ajax+jQuery realize dynamic updating of web pages

  • 2020-10-07 18:45:21
  • OfStack

views. Modifications in py

Add the corresponding request handler function:


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 or HttpResponse(json.dumps (res))

Front-end web page modification


<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(" Handle exception return! ");}
 
		
 });
	 
 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"> Please enter a query key:</label>
<input id="searchContent" type="text" size="40"></input>
 <input id="calculate" type="button" value=" determine " ></input>
</div>
 <br>
<label id="lbl1" class="cssLabelClient"> Node information </label>
<Textarea id="ClientInfoArea" readonly class="txtClientInfo"></Textarea>
</div>

#calculate is a button, click the action is bound to submit function submit_form, ajax request parameters, data contains query parameters, success is the request after the success of the action, note that the returned res needs to be json parsing before it can be used correctly: root = JSON.parse (jsondata); update (res) is a function that updates the content of a web page

Route configuration modification

urls.py as amended:


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)),
)

It is important to note that the index routing configuration is placed as close to the last line as possible to avoid routing overrides.


Related articles: