python3 django finishing (7) Django has a variety of ways to pass data from the background to the foreground.

Django has a variety of ways to pass data from the background to the foreground.

Basic form:

from django.shortcuts import render

def main_page(request):
    return render(request, 'index.html')

views pass to HTML using data

views are passed to HTML using data.

  • Code in views:
from django.shortcuts import render

def main_page(request):
    data = [1,2,3,4]
    return render(request, 'index.html', {'data': data})
  • call in html

1.htmlUse {{ }} to get data

<div>{{ data }}</div>

2. Iterable data can be iterated:

{% for item in data%}
<p>{{ item }}</p>
{% endfor %}

This method can be passed various data types, including list, dict, etc.
And in addition to {% for %}, you can also perform if judgment, size comparison, etc. Readers can search for specific usage.

JavaScript call parameters

Take a simple list as an example

# -*- coding: utf-8 -*-

import json
from django.shortcuts import render

def main_page(request):
    list = ['view', 'Json', 'JS']
    return render(request, 'index.html', {
            'List': json.dumps(list),
        })

JavaScript part:

var List = {{ List|safe }};

You can also use js's for, etc. to operate
for(var i=0;i

JavaScript Ajax dynamic page refresh

The front desk of the web page uses Ajax to send requests, and the data is processed in the background and returned to the front desk. The front desk does not refresh the web page to dynamically load data
. Django code:

def scene_update_view(request):
    if request.method == "POST":
            name = request.POST.get('name')
            status = 0
            result = "Error!"
            return HttpResponse(json.dumps({
                "status": status,
                "result": result
            }))

JS code:

 function getSceneId(scece_name, td) {
            var post_data = {
                "name": scece_name,
            };

            $.ajax({
                url: {% url 'scene_update_url' %},
                type: "POST",
                data: post_data,
                success: function (data) {
                    data = JSON.parse(data);
                    if (data["status"] == 1) {
                        setSceneTd(data["result"], scece_name, td);
                    } else {
                        alert(data["result"]);
                    }
                }
            });
        } 
JS 发送ajax请求,后台处理请求并返回status, result
在 success: 后面定义回调函数处理返回的数据,需要使用 JSON.parse(data)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324647155&siteId=291194637