程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Cooperative application of JS timer and Ajax or getjson in Django

編輯:Python

We were using the django When doing projects, it is often necessary to transfer the data received in the background to the front-end display , The most basic method is to html In the document “ Dig a hole ”({ { data }}), At the back end, the data is transmitted in the form of a dictionary , This method is the simplest one , But on some occasions , For example, the data at a certain location will change periodically , If we still use this method , You need to constantly refresh the web page , In this way, the resource consumption of the server is extremely high , So is there a way that we can not only reduce internal losses, but also make users reduce redundant operations as much as possible ?

The answer is JavaScript The timer and ajax or getJson Match

But before that, we need to know what these three things are !

  1. What is a timer ?
    JS Some native methods are provided to delay or execute a piece of code , In fact, it is a thing that can execute some code regularly !
  2. What is? ajax?
    ajax Is a technology for creating fast dynamic web pages . Through a small amount of data exchange with the server in the background ,ajax Asynchronous update of web pages . This means that you can load the entire page without reloading it , Update a part of the web page .
    I put ajax stay django The application in is understood as calling django A view function

Next, let's see how they use

Because I'm right JavaScript I don't have a thorough understanding of , And this article focuses on Django, So there is no need to repeat their principles or methods of use here , To avoid mistakes , Go directly to one of my most commonly used formats , If you are interested, you can check it yourself , Timers have a wide range of uses , Can be used to do a lot of things !
( The following code is JavaScript Code )

function xxx() {

xxx
}
var time1 = setInterval(function () {

xxx();
},100);
clearInterval(function () {

time1;
})

The above code is in the format of a timer , The main timing is in the middle ,100 each 100 Execute in milliseconds xxx function ,clearInterval The existence of the timer is that the timer can be turned off every time it is executed , Prevent resource consumption !
( The following code is JavaScript Code )

$.ajax({

type: 'GET',
url: 'http://127.0.0.1:8000/App/send/',
data: {

'data': 'SEND',
},
});

This code is the simplest ajax specifications ,type Indicates how to request a web page ,url Indicates a route to the requesting server ,data Represents the data transmitted to the server .


episode
In the use of ajax We need to download before jquery! Just go to the official website and download the file , find jquery.js Documents or jquery.min.js The file is then pasted into the project file , stay html Just quote again , I usually create a new one in the project file static file , Create a new one inside js file , hold jquery Copy to this folder , Now... At the time of reference html Write the following sentence in the file header
Make sure that before you write this sentence settings There is this configuration in the file

After everything is done, we'll be html At the end of the file

Remember to quote js Above the file ( The above is my quotation js File code )
write down

<script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script>

If you js The file under the folder is jquery.js Write directly jquery.js, Don't write like me jquery.min.js, Of course, if you don't want to download jquery It doesn't matter , You can go directly online API quote , It's just that every time you log on to a web page, the network should be good enough

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

Smart you must have guessed the timer and ajax How to cooperate !
On the right , Is to put ajax Put it in a function or write it directly in setInterval In the body of the function , This allows you to set a timing , Every hundred milliseconds (100) Or every second (1000) Access a route at a time , But I didn't say how to get background data , Just how to send data , It doesn't say how the background gets the data sent by the front end !

  1. It is very simple to get the data sent by the front end in the background , Just one sentence
    content = request.GET.get('data')
    
    This get Inside data To match the js Where the code is circled

    It looks like content The obtained data is the data sent from the front end to the background !
  2. For sending back-end data to the front-end
    What I choose here is to encapsulate the data into Json Format data is sent to the front end
    - First , stay js Write the following code in the code :
    $.getJSON('http://127.0.0.1:8000/App/sendtohtml/', function(data) {
    
    })
    
    url The route in should correspond to the function used to send data to the front end in the view function , hinder data That is, from the back end Json Dictionaries
    - stay view In the document :
    def sendtohtml(request):
    content = 'xxx'
    data = {
    
    'data': content,
    'status': 200
    }
    return JsonResponse(data=data) # Import required JsonResponse package (Alt+Enter You can import )
    
    Remember that in url Add a route to the file
    status It's the status code , Used to verify whether data transmission is normal , Numbers are unlimited , But there are usually internal regulations , Here is to use 200
    - go back to js file :
    $.getJSON('http://127.0.0.1:8000/App/sendtohtml/',function(data) {
    
    if(data['status'] === 200){
    
    htmldata = data['data'];
    // there htmldata Is the received background data 
    $('#div1').html(htmldata);
    // #div That is, the data to be changed div Of id, There is no introduction here jquery Can't use 
    // .html() Namely id by div1 Of div The data of is set to htmldata
    // There are many ways to set data , After learning js I'll know after , Here is only one simple way 
    }
    })
    
    Put the above paragraph js The code written in the timer can achieve periodic refresh !

Because there was an exam review week between the writing of this article , So there may be omissions , Welcome to correct and criticize !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved