Django Ajax序列化与反序列化

序列化与反序列是最常用的功能,有时我们需要将一个表单组打包成Json格式等然后再提交给服务端,这样可以提高效率节约带框,如下是Django配合Ajax实现的序列化与反序列化,文件上传等操作。

Ajax序列化与反序列化: 前端Ajax通过序列化发送JSON数据,后端通过反序列化接收数据并处理数据.

<!-- name: index.html -->
<div>
    <p><input type="text" name="username" placeholder="输入用户名"></p>
    <p><input type="password" name="password" placeholder="输入用户密码"></p>
    <p><button class="Send_AJAX">发送数据</button><span class="ErrorTag"></span></p>
</div>

<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(".Send_AJAX").click(function () {
        var username = $('input[name="username"]').val();
        var passowrd = $('input[name="password"]').val();

        $.ajax({
            url:"/_ajax/",
            type:"POST",
            contentType:"application/json;charset=utf-8",
            data:JSON.stringify({ username: username, password: passowrd }), // 序列化
            success:function (data) {
                var data = JSON.parse(data);        // 反序列化
                if(!data["flag"]){
                    $(".ErrorTag").html("用户名或密码错误");
                }else{
                    $(".ErrorTag").html("密码输入正确");
                }
            },
            error:function (data) {
                alert('未知错误,数据通信失败!');
            }
        });
    })
</script>

视图层

# name: views.py
from django.shortcuts import render,HttpResponse
import json

def index(request):
    return render(request,"index.html")

def _ajax(request):
    data = request.body.decode("utf-8")
    json_data = json.loads(data)         # 加载返回的json数据
    host = request.get_host()            # 得到远程主机IP地址
    port = request.get_port()            # 得到远程主机端口
    response = {}
    username = json_data.get("username")
    password = json_data.get("password")

    if username == "admin" and password == "123123":
        response['flag'] = True
    else:
        response['flag'] = False
    return HttpResponse(json.dumps(response))

路由层

# name: urls.py
from django.contrib import admin
from django.urls import path

from MyWeb import views
urlpatterns = [
    path("",views.index),
    path('_ajax/',views._ajax),
]

Ajax局部序列化与全局序列化: 实现前端标签的局部序列化与全局序列化功能.

<!--name: index.html-->
<form action="/_Ajax/" method="post" id="myForm">
    <input type="text" name="username" value="默认数据"></input>
    <select name="grade" id="grade">
        <option value="1">一年级</option>
        <option value="2">二年级</option>
    </select>

    <input name="sex" type="radio" checked="checked" value="1">男</input>
    <input name="sex" type="radio" value="0" />女</input>
    <input name="hobby" type="checkbox" value="1" />游泳</input>
    <input name="hobby" type="checkbox" value="2" />跑步</input>
    <input name="btn" id="btn" type="button" value="提交数据"></input>
</form>

<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $("#btn").click(function(){
        $.ajax({
            url: "./_Ajax/",
            type: "POST",
            //data: $("#myForm").serialize(),                 // 序列化整个myForm表单
            data: $("#myForm").serialize(":text,:checkbox"),  // 只序列化其中的两个
            success:function (data) {
                var data = JSON.parse(data);
                if(data["status"] == "ok")
                {
                    alert("后端已经接收到了.")
                }
            }
        })
    })
</script>

视图层

# name: views.py
from django.shortcuts import render,HttpResponse
import json

def index(request):
    return render(request,"index.html")

def _Ajax(request):
    username = request.POST.get("username")
    grade = request.POST.get("grade")
    sex = request.POST.get("sex")
    hobby = request.POST.get("hobby")
    print("用户名:{} 年级:{} 性别:{} 爱好:{}".format(username,grade,sex,hobby))

    return HttpResponse(json.dumps({"status":"ok"}))

路由层

# name: urls.py
from django.contrib import admin
from django.urls import path

from MyWeb import views
urlpatterns = [
    path("",views.index),
    path('_ajax/',views._ajax),
]

Ajax序列化实现简单命令工具: 我们通过定制Django,配合命令行执行功能可以实现远程命令执行页面.

<!--name: index.html-->
{% extends "admin/base_site.html" %}
{% load i18n static %}
{% block content %}
    <link rel="stylesheet" href="https://lyshark.com/cdn/xterm.css" />
    <link rel="stylesheet" href="https://lyshark.com/cdn/bootstrap3.css" />
    <script src="https://lyshark.com/cdn/xterm.js"></script>
    <script src="https://lyshark.com/cdn/jquery.js"></script>

    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">命令执行CMD</h3>
        </div>
        <div class="panel-body">
              <div id="terminal"></div>
        </div>
        <div class="panel-footer">
            <input type="text" id="address" placeholder="主机地址" style="200px;height:40px"/>
            <input type="text" id="command" placeholder="执行命令" style="400px;height:40px"/>
            <input type="button" value="执行命令" onclick="show()">
        </div>
    </div>
    <script type="text/javascript">
      var window_width = $(window).width()-200;
      var window_height = $(window).height()-300;
      var term = new Terminal(
            {
                cols: Math.floor(window_width/9),
                rows: Math.floor(window_height/20),
                useStyle:false,
                convertEol: true,
                cursorBlink:false,
                cursorStyle:null,
                rendererType: "canvas",
            }
    );
    term.open(document.getElementById('terminal'));
      function show(){
          var address = $("#address").val();
          var command = $("#command").val();
          console.log(command);
          $.ajax({
              url:"/term/",
              type:"POST",
              contentType:"application/json;",
              data: JSON.stringify({"address":address,"command":command}),
              success:function (res) {
                  term.clear();
                  term.writeln(res);
                  term.writeln("x1B[1;3;32m 执行时间: x1B[0m" + myDate.toLocaleString() +
                          "x1B[1;3;33m IP地址: x1B[0m" + address + "x1B[1;3;34m 命令: x1B[0m" +
                          command );
              }
          });
      }
    </script>
{% endblock %}

视图层

# name: views.py
from django.shortcuts import render,HttpResponse
import paramiko,json

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def ssh_shell(address,username,password,port,command):
    ssh.connect(address,port=port,username=username,password=password)
    stdin, stdout, stderr = ssh.exec_command(command)
    result = stdout.read()
    if not result:
        result=stderr.read()
    ssh.close()
    return result.decode()

def term(request):
    if request.method == "POST":
        data = request.body.decode("utf-8")
        json_data = json.loads(data)
        address = json_data.get("address")
        command = json_data.get("command")
        if len(data) >=2:
            ret = ssh_shell(address,"root","123","22",command)
            return HttpResponse(ret)
        else:
            return HttpResponse("None")
    return render(request, "index.html")

路由层

# name: urls.py
from MyWeb import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('term/',views.term)
]

ajax实现伪Socket: 伪socket实现的方式就是通过短轮询的方式实现,前端一直请求后台接口。

index.html
    <script src="https://lyshark.com/cdn/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
    <link rel="stylesheet" href="https://lyshark.com/cdn/xterm/xterm.css" />
    <script src="https://lyshark.com/cdn/xterm/xterm.js"></script>

    <div class="panel panel-primary">
        <div class="panel-footer">
            <input type="text" id="command" placeholder="执行命令" style="400px;height:40px"/>
            <input type="button" value="执行命令" onclick="sendData()">
        </div>
    </div>
    <script type="text/javascript">
        $(
            <!--设置定时器-->
            function () {
                fetchData();
                setInterval(fetchData, 100);
            }
        );

        <!-- 接收数据走GET-->
        function fetchData(){
            $.ajax({
                url:"/_ajax/",
                type:"GET",
                dataType: 'json',
                success:function (recv) {
                    console.log(recv.response);
                }
            })
        }

        <!-- 发送数据默认走POST-->
        function sendData()
        {
            var command = $("#command").val();
            console.log(command);
            $.ajax({
                url:"/_ajax/",
                type:"POST",
                contentType:"application/json;",
                data: JSON.stringify({"command":command}),
                success:function (send) {

                }
            })
    }
    </script>
</head>

视图层

views.Py

from django.shortcuts import render,HttpResponse
import json

def index(request):
    return render(request,"index.html")

def _ajax(request):
    if request.method == "GET":
            return HttpResponse(json.dumps({"response": "abcde"}))
    else:
        data = request.body.decode("utf-8")
        json_data = json.loads(data)

        command = json_data.get("command")
        print(command)
        return HttpResponse("ok")

路由层

urls.Py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/',views.index),
    path('_ajax/',views._ajax)
]

Ajax 同源跨域操作: 针对同源策略的跨域读取数据

<p class="ShowList"></p>
<input type="button" value="跨域获取数据" onclick="Ajax()" />

<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function Ajax() {
        $.ajax({
            url: "http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403",
            contentType: "GET",
            dataType: "jsonp",
            jsonp: "callback",
            jsonpCallback: "list",       // 此处的List必须与网站中的callback一致
            success:function (data) {
                var week_list = data.data;
                $.each(week_list,function (key,value) {
                    //console.log(key,value);   // 0 {week: "周日", list: Array(19)}
                    var str = value.week;
                    //console.log(str)             // 周日 周一 周二
                    //$(".ShowList").append(str);  // 给上方标签插入数据
                    $.each(value.list,function (k,v) {
                        //console.log(k,v);  //{time: "1730", name: "《地宝当家》", link: "http://xxx.cn"}
                        var name = v.name;    // 取出电台名字
                        var link = v.link;    // 取出它的地址
                        $(".ShowList").append(name,link,"</br>");  // 获取到电台节目
                    });
                });
            }
        });
    }
</script>

Ajax实现文件上传操作: 简单实现文件上传功能。

<!--name: index.html-->
<input type="file" id="upload">
<p><button class="btn">上传文件</button><span class="alert"></span></p>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(".btn").click(function(){
        var formData = new FormData();
        formData.append("file",$("#upload")[0].files[0]);
        $.ajax({
            url: "/put_file/",
            type: "POST",
            data:formData,
            contentType: false,
            processData: false,
            success:function (data) {
                $(".alert").html("上传成功")
            }
        })
    })
</script>

视图层

# name:views.py
from django.shortcuts import render,HttpResponse

def index(request):
    return render(request,"index.html")
def put_file(request):
    if request.method == "POST":
        file_obj = request.FILES.get("file")
        with open(file_obj.name,"wb") as f:
            for item in file_obj:
                f.write(item)
        return HttpResponse("上传完成")

Web命令执行工具: 实现一个简单的Web版命令行执行工具.

{% extends "admin/base_site.html" %}
{% load i18n static %}
{% block content %}
    <link rel="stylesheet" href="https://lyshark.com/cdn/xterm.css" />
    <link rel="stylesheet" href="https://lyshark.com/cdn/bootstrap3.css" />
    <script src="https://lyshark.com/cdn/xterm.js"></script>
    <script src="https://lyshark.com/cdn/jquery.js"></script>

    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">批量命令执行CMD工具</h3>
        </div>
        <div class="panel-body">
              <div id="terminal"></div>
        </div>
        <div class="panel-footer">
            <input type="text" id="address" placeholder="主机范围" style="200px;height:40px"/>
            <input type="text" id="command" placeholder="执行命令" style="400px;height:40px"/>
            <input type="button" value="执行命令" onclick="show()">
        </div>
    </div>
    <script type="text/javascript">
      var window_width = $(window).width()-200;
      var window_height = $(window).height()-300;
      var term = new Terminal(
            {
                cols: Math.floor(window_width/9),
                rows: Math.floor(window_height/20),
                useStyle:false,
                convertEol: true,
                cursorBlink:true,
                cursorStyle:null,
                rendererType: "canvas",
            }
    );
    term.open(document.getElementById('terminal'));
      function show(){
          var address = $("#address").val();
          var command = $("#command").val();
          console.log(command);
          $.ajax({
              url:"/term/",
              type:"POST",
              contentType:"application/json;",
              data: JSON.stringify({"address":address,"command":command}),
              success:function (res) {
                  term.writeln(res);
              }
          });
      }
    </script>
{% endblock %}

视图层

from django.shortcuts import render,HttpResponse
import paramiko,json,time

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def ssh_shell(address,username,password,port,command):
    try:
        ssh.connect(address,port=port,username=username,password=password)
        stdin, stdout, stderr = ssh.exec_command(command)
        result = stdout.read()
        if not result:
            result=stderr.read()
        ssh.close()
        return result.decode()
    except Exception:
        ssh.close()
def term(request):
    if request.method == "POST":
        data = request.body.decode("utf-8")
        json_data = json.loads(data)
        address = json_data.get("address")
        command = json_data.get("command")
        if len(address) >=2 and len(command) >=2:
            ret = ssh_shell(address,"root","123","22",command)
            if ret !=None:
                times = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                times = "x1B[1;3;25m [执行成功] x1B[0m ---> x1B[1;3;32m 执行时间:[{}] x1B[0m".format(times)
                address = "x1B[1;3;33m 地址:[ {} ] x1B[0m".format(address)
                command = "x1B[1;3;35m 命令:[ {} ] x1B[0m".format(command)
                retn = times + address + command
                return HttpResponse(retn)
            else:
                times = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                times = "x1B[1;3;31m [执行失败] x1B[0m ---> x1B[1;3;32m 执行时间:[{}] x1B[0m".format(times)
                address = "x1B[1;3;33m 地址:[ {} ] x1B[0m".format(address)
                command = "x1B[1;3;35m 命令:[ {} ] x1B[0m".format(command)
                retn = times + address + command
                return HttpResponse(retn)
        else:
            return HttpResponse("Error")
    return render(request, "index.html")

路由层

from MyWeb import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('term/',views.term)
]

批量CMD执行工具: 利用DjangoAdmin与Socket通信实现的主机批量执行并回显.

<!--name:index.html-->
{% extends "admin/base_site.html" %}
{% load i18n static %}
{% block content %}
    <link rel="stylesheet" href="https://lyshark.com/cdn/xterm.css" />
    <link rel="stylesheet" href="https://lyshark.com/cdn/bootstrap3.css" />
    <script src="https://lyshark.com/cdn/xterm.js"></script>
    <script src="https://lyshark.com/cdn/jquery.js"></script>
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">批量命令执行CMD工具</h3>
        </div>
        <div class="panel-body">
              <div id="terminal"></div>
        </div>
        <div class="panel-footer">
            <input type="text" id="address" placeholder="主机范围 127.0.0.1-100" style="200px;height:40px"/>
            <input type="text" id="command" placeholder="执行命令 ls -lh " style="400px;height:40px"/>
            <input type="button" id="send_message" value="批量执行">
        </div>
    </div>
    <script type="text/javascript">
        $(function(){
            var window_width = $(window).width()-200;
            var window_height = $(window).height()-300;
            var term = new Terminal(
            {
                cols: Math.floor(window_width/9),
                rows: Math.floor(window_height/20),
                convertEol: true,
                cursorBlink:false,
            });
            var sock = new WebSocket("ws://" + window.location.host + "/echo/");
            sock.onopen = function () {
                term.open(document.getElementById('terminal'));
                console.log('WebSocket Open');
            };
            sock.onmessage = function (recv) {
                if(recv.data.substring(0,7) == "[Suces]"){
                    term.writeln("x1B[1;3;32m " + recv.data + "x1B[0m");
                }else{
                    term.writeln("x1B[1;3;31m " + recv.data + "x1B[0m");
                }

            };
            $('#send_message').click(function () {
                var message ={"address":null,"command":null};
                message['address'] = $("#address").val();
                message['command'] = $("#command").val();
                var send_data = JSON.stringify(message);
                window.sock.send(send_data);
            });
            window.sock = sock;
        });
    </script>
{% endblock %}

视图层

# name:views.py
from django.shortcuts import render
from dwebsocket.decorators import accept_websocket
import paramiko,time

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def ssh_shell(address,username,password,port,command):
    try:
        ssh.connect(address,port=port,username=username,password=password,timeout=1)
        stdin, stdout, stderr = ssh.exec_command(command)
        result = stdout.read()
        if not result:
            result=stderr.read()
        ssh.close()
        return result.decode()
    except Exception:
        return 0

def CalculationIP(Addr_Count):
    ret = []
    try:
        IP_Start = str(Addr_Count.split("-")[0]).split(".")
        IP_Heads = str(IP_Start[0] + "." + IP_Start[1] + "." + IP_Start[2] +".")
        IP_Start_Range = int(Addr_Count.split(".")[3].split("-")[0])
        IP_End_Range = int(Addr_Count.split("-")[1])
        for item in range(IP_Start_Range,IP_End_Range+1):
            ret.append(IP_Heads+str(item))
        return ret
    except Exception:
        return 0

@accept_websocket
def echo(request):
    if not request.is_websocket():
        return render(request, "index.html")
    else:
        for message in request.websocket:
            data = eval(message)
            Addr_list = CalculationIP(data['address'])
            command = data['command']
            for ip in Addr_list:
                ret = ssh_shell(ip,"root","123","22",command)
                if ret != 0:
                    times = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                    retn = "[Suces] ---> " + str(times) + "      " +  command + "      " + ip
                    request.websocket.send(retn)
                else:
                    times = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                    retn = "[Error] ---> " + str(times) + "      " +  command + "      " + ip
                    request.websocket.send(retn)

路由层

# name:urls.py
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path("echo/",views.echo)
]

许可协议: 文章中的代码均为学习时整理的笔记,博客中除去明确标注有参考文献的文章,其他文章【均为原创】作品,转载请务必【添加出处】,您添加出处是我创作的动力!
反制措施: 《点我预览协议》
原文地址:https://www.cnblogs.com/LyShark/p/14386789.html