Home Web Front-end JS Tutorial How to use Ajax in Django

How to use Ajax in Django

Apr 04, 2018 pm 05:38 PM
ajax django Instructions

This time I will bring you how to use Ajax in Django. What are the precautions for using Ajax in Django? The following is a practical case, let's take a look.

Django is a free open source website framework developed in Python, which can be used to quickly build high-performance, elegant websites!

AJAX = Asynchronous

JavaScript and XML (Asynchronous JavaScript and XML).

AJAX is not a new

programming language, but a new way of using existing standards.

AJAX is the art of exchanging data with a server and updating parts of a web page without reloading the entire page.

Ajax

Many times, when we request an operation on a web page, we do not need to refresh the page. The technology to achieve this function requires Ajax!

ajax in jQuery can realize the function of requesting or submitting data to the background without refreshing the page. We still use it to do ajax in django, so download jquey first , the higher the version, the better.

1. Simple ajax sendingData type:

html code: Here we only send a simple string

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-">
<title></title>
</head>
<body>
<input type="button" onclick="AjaxSubmit();" value="提交">
<script src="/static/jquery-...min.js"></script>
<script>
function AjaxSubmit(){
var host = '...';
var port = '';
$.ajax({
url:"/app/ajax_submit/",
type:'POST',
data:{host:host,port:port},
success: function (arg) {
}
});
}
</script>
</body>
</html>
Copy after login
views.py

# coding:utf-8
from django.shortcuts import render,HttpResponse
def ajax_submit(request):
print request.POST #客户端发来的数据
return render(request,'ajax_submit.html')
Copy after login
Printed data style in app under django:

2. Ajax sends complex data types:

html code: Here we only send a list containing the dictionary data type

Since the data type sent is in the format of a list dictionary, we must convert them into string form in advance , otherwise the data format received by the background program is not the type we want, so when transmitting data through ajax, we need the data style printed out by JSON

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-">
<title></title>
</head>
<body>
<input type="button" onclick="AjaxSubmit_set();" value="提交集合">
<script src="/static/jquery-...min.js"></script>
<script>
function AjaxSubmit_set(){
var data_list = [
{'name':'chenchao','age':},
{'name':'lisi','age':},
{'name':'wangwu','age':}
];
$.ajax({
url:"/app/ajax_submit_set/",
type:'POST',
tradition:true, 原生模式
data:{data:JSON.stringify(data_list)},
success: function (arg) {
}
});
}
</script>
</body>
</html>
Copy after login
views.py

def ajax_submit_set(request):
print request.POST
return render(request,'ajax_submit.html')
Copy after login
in the app under django :

3. Wait a moment, it’s not over yet.

Although we have implemented the function, it is not enough because it does not look very professional, so we will deal with it a little bit.

success: function (arg) { } If ajax submits data successfully, the function inside will be automatically executed

html code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-">
<title></title>
</head>
<body>
<input type="button" onclick="AjaxSubmit();" value="提交">
<input type="button" onclick="AjaxSubmit_set();" value="提交集合">
<script src="/static/jquery-...min.js"></script>
<script>
function AjaxSubmit(){
var host = '...';
var port = '';
$.ajax({
url:"/app/ajax_submit/",
type:'POST',
data:{host:host,port:port},
success: function (arg) {
}
});
}
function AjaxSubmit_set(){
var data_list = [
{'name':'chenchao','age':},
{'name':'lisi','age':},
{'name':'wangwu','age':}
];
$.ajax({
url:"/app/ajax_submit_set/",
type:'POST',
tradition:true,
data:{data:JSON.stringify(data_list)},
success: function (arg) { //如果程序执行成功就会执行这里的函数
var callback_dic = $.parseJSON(arg);
if(callback_dic.status){ 
alert('成功');
}else{
alert(callback_dic.error); //把错误的信息从后台提出展示出来
}
}
});
}
</script>
</body>
</html>
Copy after login

views.py in app under django

# coding:utf-
from django.shortcuts import render,HttpResponse,redirect
def ajax_submit(request):
print request.POST
return render(request,'ajax_submit.html')
import json
def ajax_submit_set(request):
ret = {'status': True,'error': ""}
try:
print request.POS
except Exception, e:
ret['status'] = False
ret['error'] = str(e)
j_ret = json.dumps(ret)
return HttpResponse(j_ret)
Copy after login

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); 
}
});
Copy after login
The return method of the corresponding code in the backend is as follows:

if act_job == 'ajax_handle':
return HttpResponse('ajax_handle')
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Detailed explanation of the principles, advantages and disadvantages of Ajax

ajax and iframe framework to implement image file upload (Detailed picture and text)

The above is the detailed content of How to use Ajax in Django. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use DirectX repair tool? Detailed usage of DirectX repair tool How to use DirectX repair tool? Detailed usage of DirectX repair tool Mar 15, 2024 am 08:31 AM

The DirectX repair tool is a professional system tool. Its main function is to detect the DirectX status of the current system. If an abnormality is found, it can be repaired directly. There may be many users who don’t know how to use the DirectX repair tool. Let’s take a look at the detailed tutorial below. 1. Use repair tool software to perform repair detection. 2. If it prompts that there is an abnormal problem in the C++ component after the repair is completed, please click the Cancel button, and then click the Tools menu bar. 3. Click the Options button, select the extension, and click the Start Extension button. 4. After the expansion is completed, re-detect and repair it. 5. If the problem is still not solved after the repair tool operation is completed, you can try to uninstall and reinstall the program that reported the error.

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to use Baidu Netdisk-How to use Baidu Netdisk How to use Baidu Netdisk-How to use Baidu Netdisk Mar 04, 2024 pm 09:28 PM

Many friends still don’t know how to use Baidu Netdisk, so the editor will explain how to use Baidu Netdisk below. If you are in need, hurry up and take a look. I believe it will be helpful to everyone. Step 1: Log in directly after installing Baidu Netdisk (as shown in the picture); Step 2: Then select "My Sharing" and "Transfer List" according to the page prompts (as shown in the picture); Step 3: In "Friend Sharing", you can share pictures and files directly with friends (as shown in the picture); Step 4: Then select "Share" and then select computer files or network disk files (as shown in the picture); Fifth Step 1: Then you can find friends (as shown in the picture); Step 6: You can also find the functions you need in the "Function Treasure Box" (as shown in the picture). The above is the editor’s opinion

What is the KMS activation tool? How to use the KMS activation tool? How to use KMS activation tool? What is the KMS activation tool? How to use the KMS activation tool? How to use KMS activation tool? Mar 18, 2024 am 11:07 AM

The KMS Activation Tool is a software tool used to activate Microsoft Windows and Office products. KMS is the abbreviation of KeyManagementService, which is key management service. The KMS activation tool simulates the functions of the KMS server so that the computer can connect to the virtual KMS server to activate Windows and Office products. The KMS activation tool is small in size and powerful in function. It can be permanently activated with one click. It can activate any version of the window system and any version of Office software without being connected to the Internet. It is currently the most successful and frequently updated Windows activation tool. Today I will introduce it Let me introduce to you the kms activation work

How to use potplayer-How to use potplayer How to use potplayer-How to use potplayer Mar 04, 2024 pm 06:10 PM

Potplayer is a very powerful media player, but many friends still don’t know how to use potplayer. Today I will introduce how to use potplayer in detail, hoping to help everyone. 1. PotPlayer shortcut keys. The default common shortcut keys for PotPlayer player are as follows: (1) Play/pause: space (2) Volume: mouse wheel, up and down arrow keys (3) forward/backward: left and right arrow keys (4) bookmark: P- Add bookmarks, H-view bookmarks (5) full screen/restore: Enter (6) multiple speeds: C-accelerate, 7) Previous/next frame: D/

How to merge cells using shortcut keys How to merge cells using shortcut keys Feb 26, 2024 am 10:27 AM

How to use the shortcut keys for merging cells In daily work, we often need to edit and format tables. Merging cells is a common operation that can merge multiple adjacent cells into one cell to improve the beauty of the table and the information display effect. In mainstream spreadsheet software such as Microsoft Excel and Google Sheets, the operation of merging cells is very simple and can be achieved through shortcut keys. The following will introduce the shortcut key usage for merging cells in these two software. exist

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

What is PyCharm? Function introduction and detailed explanation of usage What is PyCharm? Function introduction and detailed explanation of usage Feb 20, 2024 am 09:21 AM

PyCharm is a professional Python integrated development environment (IDE) developed by JetBrains. It provides Python developers with powerful functions and tools, making writing Python code more efficient and convenient. PyCharm supports multiple operating systems, including Windows, macOS and Linux, and also supports multiple Python versions, and provides a wealth of plug-ins and extension functions to facilitate developers to customize the IDE environment according to their own needs. P

See all articles