Using Ajax
- Using a view to pass data to a template through context requires loading a static page of the completed template, executing the model code, generating the most HTML, and returning it to the browser, which integrates the page with the data, with poor extensibility
- Improved solution: Get the data through Ajax and render the data to the interface via DOM manipulation
- It is recommended to use the framework's AJAX-related methods, not to use XMLHttpRequest objects, because the operation is cumbersome and not easy to find errors
- The $.ajax, $.get, and $.post methods are available in the jquery framework for asynchronous interaction
- Due to CSRF constraints, it is recommended to use $.get
- Example: Realizing the choice of a provincial city
- Final implementation effect
Introduction of JS File
- JS file belongs to static file, create directory structure
modifying settings.py settings for static files
Static_url = '/static/'staticfiles_dirs = [ os.path.join (Base_dir, ' static '),]
Defining the model in models.py
Class Areainfo (models. Model): AID = models. Integerfield (primary_key=True) Atitle = models. Charfield (max_length=20) Aparea = models. ForeignKey (' Areainfo ', null=true)
Build migration
Python manage.py Makemigrationspython manage.py Migrate
Populating the table with sample data by Workbench
- See "Provinces, cities, and regions. SQL"
- Note Replace the name of the table with the complete
Writing a view in views.py
- Index for Presentation pages
- GETAREA1 for returning provincial data
- GETAREA2 is used to return city and district information according to the province and city number, and the format is a Dictionary object
From django.shortcuts import renderfrom django.http import jsonresponsefrom models import areainfodef Index (Request): return render (Request, ' ct1/index.html ') def getArea1 (request): List = AreaInfo.objects.filter (aparea__isnull=True) list2 = [] For a in list:list2.append ([A.aid, A.atitle]) Return Jsonresponse ({' Data ': List2}) def getArea2 (Request, PID): List = AreaInfo.objects.filter (aparea_id= pid) List2 = [] for A in List:list2.append ({' id ': a.aid, ' title ': A.atitle}) return Jsonresponse ({' Da Ta ': list2})
Configuring Urlconf in urls.py
From Django.conf.urls import urlfrom. Import viewsurlpatterns = [ url (r ' ^$ ', views.index), URL (R ' ^area1/$ ', views.getarea1), url (r ' ^ ([0-9]+)/$ ', VIEWS.GETAREA2),]
The URL for this app is included in the main urls.py
From Django.conf.urls import include, Urlfrom django.contrib import adminurlpatterns = [ url (r ' ^ '), Include (' Ct1.urls ', namespace= ' Ct1 '), url (r ' ^admin/', include (Admin.site.urls)),]
Define Template index.html
- The directory structure in the project
- Modify the settings.py templates entry, set the dirs value
' DIRS ': [Os.path.join (Base_dir, ' templates ')],
- Define template file: Contains three select tags, each of which stores information about the city
<! DOCTYPE html>
To introduce a jquery file in a template<script type= "Text/javascript" src= "Static/ct1/js/jquery-1.12.4.min.js" ></script>
Writing JS Code
- Bind Change Event
- Making an asynchronous request
- Adding elements using the DOM
<script type= "Text/javascript" >$ (function () {$.get (' area1/'), function (DIC) {pro=$ (' #pro ' ) $.each (dic.data,function (Index,item) { Pro.append (' <option value= ' +item[0]+ ' > ' +item[1]+ ' </option> ' ); }) }); $ (' #pro ' ). Change (function () {$.post ($ (). Val () + '/' , function (DIC) {city=$ (' #city ' ); CIT Y.empty (). Append (' <option value= ' > Please select City </option> ' ); $.each (Dic.data,function (Index,item) { City.append (' <option value= ' +item.id+ ' > ' +item.title+ ' </option> ' );}) }); }); $ (' #city ' ). Change (function () {$.post ($ (). Val () + '/' , function (DIC) {dis=$ (' #dis ' ); Dis.empty ( ). Append (' <option value= ' > Please select County </option> ' ); $.each (Dic.data,function (index,item) {dis.append (' <option value= ' +item.id+ ' > ' +item.title+ ' </option> ' ); }) }) }); }); </script>
Django uses jquery to complete Ajax