Ajax and DjangoAjax in Django
Django is a free open-source website framework developed by Python. It can be used to quickly build high-performance and elegant websites!
AJAX = Asynchronous JavaScript and XML (Asynchronous JavaScript and XML ).
AJAX is not a new programming language, but a new method that uses existing standards.
AJAX is the art of exchanging data with the server and updating some webpages without reloading the entire page.
Ajax
Most of the time, we do not need to refresh the page when requesting operations on the webpage. Ajax is required to implement this function!
Ajax in jQuery can be used to request or submit data to the background without refreshing a new page. We still use it for ajax in django. Therefore, download jquey first, and the higher the version, the better.
I. Simple data types sent by ajax:
Html code: Here we only send a simple string
<! DOCTYPE html>
Views. py in the app under django
# Coding: utf-8from django. shortcuts import render, HttpResponsedef ajax_submit (request): print request. POST # return render(request,'ajax_submit.html ')
Printed data style:
Ii. complex data types sent by ajax:
Html code: Here we only send a list containing Dictionary data types
Because the data type sent is in the list dictionary format, we need to convert them into strings in advance. Otherwise, the data format received by the background program is not the type we want, therefore, JSON is required for ajax data transmission.
<! DOCTYPE html>
Views. py in the app under django
def ajax_submit_set(request):print request.POSTreturn render(request,'ajax_submit.html')
Printed data style:
3. Wait a moment.
Although we have implemented functions, this is not enough because it is not very professional, so we will handle it a little.
Success: function (arg) {} If ajax successfully submits data, the above function is automatically executed.
Html code:
<! DOCTYPE html>
Views. py in the app under django
# coding:utf-from django.shortcuts import render,HttpResponse,redirectdef ajax_submit(request):print request.POSTreturn render(request,'ajax_submit.html')import jsondef ajax_submit_set(request):ret = {'status': True,'error': ""}try:print request.POSexcept Exception, e:ret['status'] = Falseret['error'] = str(e)j_ret = json.dumps(ret)return HttpResponse(j_ret)
Use of ajax in Django
The front-end ajax code is as follows:
$.ajax({type:'GET',url:'/store/ds_mgmt_wx/ajax_handle',dataType:'html',success:function(data){alert(data);},error:function(data){alert(data); }});
The Return Method of the corresponding back-end code is as follows:
if act_job == 'ajax_handle':return HttpResponse('ajax_handle')
I will introduce the Ajax editor in Django to you here, and hope to help you!
Articles you may be interested in:
- Django uses ajax to initiate a request to return JSON data
- How does the Django framework use the ajax post method?
- How to solve the 403 error in django's use of ajax post Data