前端之js、jquery、ajax、mui、ui

css引入

js

jquery

ajax

1.post请求

2.ajax发送文件

3.get请求

4.ajax通过django的CSRF校验

mui

ui与NET

ztree

一、css之样式引入

<link rel="shortcut icon" href="{% static 'img/luffy-study-logo.png' %} ">
<link rel="stylesheet" href="{% static 'plugins/font-awesome/css/font-awesome.css' %} "/>
<link rel="stylesheet" href="lib/example.css">
<link rel="icon" href="//s01.mifile.cn/favicon.ico" type="image/x-icon">

二、js

#js、jquery引入
<script src="{% static 'plugins/jquery/jquery.min.js' %}"></script>
<script type="text/javascript" src="/static/js/jquery-ui.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
#判断语句
    if("{{ pk }}"=="0"){
        url="{% url 'createproject' %}"
    }else{
        url="{% url 'editproject' pk %}"
    }

if(Object.values(res.msg.unreachable).length !=0){
    var data_unreachable=res.msg.unreachable;
    $.each(data_unreachable,function (k,v) {
        msg=msg+"<font color=red>"+ k + "| UNREACHABLE!  >>\n";
        msg=msg+v.command.msg+"</font>\n";
    })
}

 

#循环语句
var minute_select = $("#minute_select");
minute_select.append("<option value=*>*</option>");
for (var i = 0; i < 60; i++) {
    minute_select.append("<option value=" + i + ">" + i + "</option>");
    if (i != 0 && i != 1) {
        minute_select.append("<option value=*/" + i + ">*/" + i + "</option>")
    }
}
#函数
function (d) {
     $("#tag_select").append("<option value='"+d+"'>"+d+"</option>")
}
$.post(
    "http://192.168.11.40:9527/open_toy",
    {device_key: device_key},
    function (data) {
        console.log(data);
        if (data.code == 0) {
            document.getElementById("title").innerText = data.name;
            toy_id = data.toy_id;
            create_ws(toy_id);
        }
        document.getElementById("player").src = "http://192.168.11.40:9527/get_music/" + data.music;
    },
    "json"
);

websocket的使用

    function create_ws(toy_id) {
        ws = new WebSocket("ws://192.168.11.40:9528/toy/" + toy_id); // 456
        ws.onmessage = function (eventMessage) { //456.onmessage
            var recv_msg = JSON.parse(eventMessage.data);
            console.log(recv_msg);
            if (recv_msg.music) {
                document.getElementById("player").src = "http://192.168.11.40:9527/get_music/" + recv_msg.music;
            } else {
                document.getElementById("from_user").innerText = recv_msg.from_user;
                document.getElementById("from_user_type").innerText = recv_msg.friend_type;
                document.getElementById("player").src = "http://192.168.11.40:9527/get_chat/" + recv_msg.chat;
            }
        };
        ws.onclose = function () {
            create_ws(toy_id);
        };
    }

js绑定事件

document.getElementById('acc').addEventListener('tap', function() {})

三、jquery

标签的取值与赋值

$("#cron").addClass("active");
$("#tag_select").append("<option value='0'>"+"---------"+"</option>");
$("#commit_select").empty();
$("#count_span").text(0);
$("#createBtn").attr('disabled', 'disabled'); //disabled 当前图标不可点
$("#command_text").val();
$("#com_span").html(msg);
$("#time_span").text(time);
$(".tag_name").hide();
$(".bra_name").show();
$("select").select2();

get与post请求

$.get({
    url: "/gettag/" + team_val,
    success: function (res) {
        data = res.data;
        data.forEach(function (d) {
            $("#tag_select").append("<option value='" + d + "'>" + d + "</option>")
        })

    }
})
$.get({
      url: "/getcommit/" + team_val + "/" + bra_val,
      success: function (res) {
          data = res.data;
          data.forEach(function (d) {
              console.log(d);
              $("#commit_select").append("<option value='" + d.id + "'>" + d.message + "</option>")
          })

      }
  })
$.post({
        url: "{% url 'createcomm' %}",
        data: {
            nodes: node_ips,
            command: $("#command_text").val()
        },
        success: function (res) {
            var msg="";
            $("#createBtn").attr('disabled', null); //disabled 当前图标不可点
            $("#iconWait").removeClass("fa fa-spinner fa-spin") //loading
            console.log(res.msg);
            if(Object.values(res.msg.ok).length !=0){
                var data_ok=res.msg.ok;
                $.each(data_ok,function (k,v) {
                    msg=msg+"<font color=yellow>"+ k + "| CHANGED | rc=0 >>\n";
                    msg=msg+v.command.stdout+"</font>\n";
                })
            }
            $("#com_span").html(msg);
        }
    }) 
示例2:
$.post("http://192.168.11.40:9527/recv_msg", {
    from_user: from_user,
    to_user: toy_id
}, function (data) {
    console.log(data);
    var chat_info = data.pop();
    document.getElementById("player").src = "http://192.168.11.40:9527/get_chat/" + chat_info.chat;
    document.getElementById("player").onended = function () {
        if(data.length == 0){
            return
        }
        document.getElementById("player").src = "http://192.168.11.40:9527/get_chat/" + data.pop().chat;
    }
}, "json")
    $("select").select2();
    $(".tag_name").hide();
    /*通过不同的单选框实现不同的input显示与隐藏*/
    $(".id2").change(function () {
        /* id2:checked代表当前选中的值*/
        var type_check = $(".id2:checked").val()
        if (type_check == "bra") {
            $(".tag_name").hide();
            $(".bra_name").show();
            $(".bra_commit").show()
        } else {
            /* show 显示
               hide 隐藏
               empty 清空
            */
            $(".tag_name").show();
            $(".bra_name").hide();
            $(".bra_commit").hide();
            $(".tag_name").empty();
            $("#tag_select").append("<option value='0'>" + "---------" + "</option>")
            var team_val = $('#id_team').val() || 0;
            /* 获取tag标签*/
            $.get({
                url: "/gettag/" + team_val,
                success: function (res) {
                    data = res.data;
                    data.forEach(function (d) {
                        $("#tag_select").append("<option value='" + d + "'>" + d + "</option>")
                    })

                }
            })
        }
    });

事件绑定

$(".del-user").on("click", function (e) {
    e.preventDefault(); //取消原来自带的属性
    var url=$(this).attr("data-url");
    ui.confirm("请确认是否删除本条记录",function () {
        Net.get({
            url: url,
            reload:true
        })
    });
})

四、ajax

1.post请求

 

$('[name="user"]').blur(function () {
    $.ajax({
        url: '/check/',
        type: 'post',
        data: {'user': $('[name="user"]').val()},
        success: (res) => {
            $(this).next().text(res.msg)
        }
    })
}).focus(function () {
    $(this).next().text('')
})

post 

$.ajax({
url: serv + "/toy_uploader",
type: 'post',
processData: false,
contentType: false,
data: formdata,
dataType: 'json',
success: function (data) {
console.log(data);
if(data.DATA.code == 0){
document.getElementById("player").src =
"http://192.168.11.40:9527/get_music/SendOK.mp3";
}
var send_str = {
to_user: document.getElementById("from_user").innerText,
from_user: toy_id,
friend_type:data.DATA.friend_type,
chat: data.DATA.filename
};
ws.send(JSON.stringify(send_str));
}
})

2.ajax发送文件

$('#b1').click(function () {
    var form_obj = new FormData();
    form_obj.append('x1', $('#f1')[0].files[0]);
    $.ajax({
        url: '/upload/',
        type: 'post',
        data: form_obj,
        processData:false,
        contentType:false,
        success: function (res) {
            alert('OK')
        }
    })
}) 

 

3.get请求

$.ajax({
    url: `http://127.0.0.1:8080/login?username=${username}`,
    type:'get',
    success:function (data) {
        DOM操作
    }
});
$.ajax({
    url: url,
    data: request,
    dataType: "json",
    success: function( data ) {
        response( data );
    },
    error: function() {
        response([]);
    }
}); 

4.ajax通过django的CSRF校验

#前提条件:保证访问的页面有csrftoken的cookie

#一:模板中使用csrf_token标签

#二:给视图加装饰器
from django.views.decorators.csrf import ensure_csrf_cookie  # 确保访问某个视图有csrf_cookie
#方式一:
$.ajax({
    url: '/calc/',
    type: 'post',
    data: {
        csrfmiddlewaretoken:$('[name="csrfmiddlewaretoken"]').val() ,
        i1: $('[name="i1"]').val(),
        i2: $('[name="i2"]').val(),
    },
    success: function (res) {
        $('[name="i3"]').val(res)
    }
})

#方式二:
$('#b2').click(function () {

    $.ajax({
        url: '/calc2/',
        type: 'post',
        headers:{
           'X-csrftoken': $('[name="csrfmiddlewaretoken"]').val(),
        }, 
        data: {
            i1: $('[name="ii1"]').val(),
            i2: $('[name="ii2"]').val(),
        },
        success: function (res) {
            $('[name="ii3"]').val(res)
        }
    })
});

#文件:
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    beforeSend: function (xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
}); 

 

五、mui

mui.init();
var Sdata = null;
mui.plusReady(function() {
    Sdata = plus.webview.currentWebview();
    document.getElementById("req_info").innerText = Sdata.req_info;
});

document.getElementById('acc').addEventListener('tap', function() {
    mui.post(window.serv + '/acc_req',{
            req_id:Sdata._id,
            remark:document.getElementById("remark").value
        },function(data){
            
        },'json'
    );
})
var reco = null;
document.getElementById('speech').addEventListener('hold', function() {
    mui.toast('按住了');
    reco = plus.audio.getRecorder();
    reco.record({
        filename: "_doc/audio/",
        format: "amr"
    }, function(file_path) {
        //                    console.log(args_str);
        create_upload_task(file_path);
    })
});
document.getElementById('speech').addEventListener('release', function() {
    mui.toast("松开了");
    reco.stop();
});
document.getElementById('add_fri').addEventListener('tap',function () {
        mui.openWindow({
            url: "scan.html",
            id: "scan.html",
            extras:{type:"toy",create_toy_id:Sdata._id}
        });
})
#index.html中
document.addEventListener("send_chat", function(event) {
    var s = JSON.stringify(event.detail);
    ws.send(s);
});
#其他文件中调用
mui.fire(index, 'send_chat', {
    chat: res.DATA.filename,
    to_user: Sdata.friend_id,
    from_user: window.localStorage.getItem("user_id")
})
mui.back = function(){};
mui.post(window.serv + '/add_req',{
        add_user:user_id,
        toy_id:Sdata.toy_id,
        add_type:Sdata.add_type,
        req_info:req_info,
        remark:remark
    },function(data){
        console.log(JSON.stringify(data));
    },'json'
);

六、ui与NET

$(".create-btn").on("click", function () {
    ui.box({
        "title":"创建用户",
        "remote":{% url 'createuser' %},

    });
})
$(".update-btn").on("click", function () {
    ui.box({
        "title": "创建初始化",
        "remote":{% url 'createlog' %},

    });
});
ui.confirm("请确认是否删除本条记录",function () {
    Net.get({
        url: url,
        reload:true
    })
});
$("#createBtn").on("click",function () {
    Net.post({
        url:url,
        btn:$("#createBtn"),
        data:$("#createForm").serialize(),
        go:"{% url 'projectall' %}"
    })
})

七、ztree

<script type="text/javascript" src="{% static 'plugins/zTree_v3/js/jquery.ztree.core.js' %}"></script>
<script type="text/javascript" src="{% static 'plugins/zTree_v3/js/jquery.ztree.excheck.js' %}"></script>
<script>
        $("select").select2();

        var setting = {
            view: {
                selectedMulti: false
            },
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onCheck: onCheck
            }
        };

        var clearFlag = false;

        function onCheck(e, treeId, treeNode) {
            count();
            if (clearFlag) {
                clearCheckedOldNodes();
            }
        }

        function clearCheckedOldNodes() {
            var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                nodes = zTree.getChangeCheckedNodes();
            for (var i = 0, l = nodes.length; i < l; i++) {
                nodes[i].checkedOld = nodes[i].checked;
            }
        }

        function count() {
            var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                checkCount = zTree.getCheckedNodes(true).length,
                nocheckCount = zTree.getCheckedNodes(false).length,
                changeCount = zTree.getChangeCheckedNodes().length;
            if (checkCount > 1) {
                $("#count_span").text(checkCount - 1);
            } else {
                $("#count_span").text(0);
            }

        }

        function createTree() {
            $.fn.zTree.init($("#treeDemo"), setting, {{ nodes|safe }});
            count();

            clearFlag = $("#last").attr("checked");
        }

        $(document).ready(function () {
            createTree();
            $("#init").bind("change", createTree);
            $("#last").bind("change", createTree);
        });
        /* ajax添加csrfkey*/
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        var csrftoken = getCookie('csrftoken');

        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }

        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });

        $("#createBtn").on("click", function () {
            var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                nodes = zTree.getCheckedNodes(true);
            node_ips = [];
            if(nodes.length ==0){
                alert("请选择主机")
                return
            }
            if($("#command_text").val() == ""){
                alert("请输入命令")
                return
            }
            nodes.forEach(function (node) {
                if (node.pId) {
                    node_ips.push(node.name)
                }
            });
            console.log(node_ips);
            $("#createBtn").attr('disabled', 'disabled'); //disabled 当前图标不可点
            $("#iconWait").addClass("fa fa-spinner fa-spin") //loading


            $.post({
                url: "{% url 'createcomm' %}",
                data: {
                    nodes: node_ips,
                    command: $("#command_text").val()
                },
                success: function (res) {
                    var msg="";
                    $("#createBtn").attr('disabled', null); //disabled 当前图标不可点
                    $("#iconWait").removeClass("fa fa-spinner fa-spin") //loading
                    console.log(res.msg);
                    if(Object.values(res.msg.ok).length !=0){
                        var data_ok=res.msg.ok;
                        $.each(data_ok,function (k,v) {
                            msg=msg+"<font color=yellow>"+ k + "| CHANGED | rc=0 >>\n";
                            msg=msg+v.command.stdout+"</font>\n";
                        })
                    }
                    if(Object.values(res.msg.skipped).length !=0){
                        var data_skipped=res.msg.skipped;
                        $.each(data_skipped,function (k,v) {
                            msg=msg+"<font color=cyan>"+ k + "| SKIPPED | rc=0 >>\n";
                            msg=msg+v.command.stdout+"</font>\n";
                        })
                    }
                    if(Object.values(res.msg.failed).length !=0){
                        var data_failed=res.msg.failed;
                        $.each(data_failed,function (k,v) {
                            msg=msg+"<font color=red>"+ k + "| FAILED | rc=2 >>\n";
                            msg=msg+v.command.stdout+"\n";
                            msg=msg+v.command.stderr+"</font>\n";
                        })
                    }
                    if(Object.values(res.msg.unreachable).length !=0){
                        var data_unreachable=res.msg.unreachable;
                        $.each(data_unreachable,function (k,v) {
                            msg=msg+"<font color=red>"+ k + "| UNREACHABLE!  >>\n";
                            msg=msg+v.command.msg+"</font>\n";
                        })
                    }

                    $("#com_span").html(msg);
                }
            })
        })

    </script>

 

posted @ 2019-06-06 20:02  海予心  阅读(255)  评论(0编辑  收藏  举报