JS第三方插件

kindediter

# textarea,用于富文本输入
<textarea id="editor_id" name="content" style="width:700px;height:300px;"></textarea>
{% csrf_token %} #加入csrf_token,提交时,手动拿到token去提交
<button onclick="submit();">回复</button>
# 使用kindediter,引入相关js
    <script>window.jQuery || document.write('<script src="/static/js/jquery3.7.1.js"><\/script>')</script>
    <script charset="utf-8" src="/static/plugins/kindeditor/kindeditor-all.js"></script>
    <script charset="utf-8" src="/static/plugins/kindeditor/lang/zh-CN.js"></script>

# kindeditor的相关代码
        KindEditor.ready(function(K) {
            window.editor = K.create('#editor_id', {
                allowFileManager : true,
                uploadJson : '/uploadimg_kindeditor/', #设置图片上传的目录
                afterUpload : function(url) {
                    this.sync()   #上传完成后同步文本内容
                },
                items : [
                    'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
                    'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
                    'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
                    'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
                    'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
                    'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
                    'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
                    'anchor', 'link', 'unlink', '|', 'about'
                ]
            });
        });
        function submit() {
            editor.sync(); #同步编辑器的内容
            dic = {};
            key1 = 'csrfmiddlewaretoken';
            cs = document.getElementsByName(key1)[0];
            dic[key1] = cs.value;  # 拿到csrf_token
            dic["content"] = document.getElementById('editor_id').value; // 原生API;
            $.post({
                url: '/{{ article.blog.site }}/article/{{  article.id }}/new_comment/',
                data: dic,
                dataType: 'JSON',
                success: function (arg) {
                    if (arg.error==0){
                        ul = document.getElementById('ulComments');
                        appendCommentElement(arg.message,ul); #js代码生成一条评论html
                    }
                }
            });
        }

图片上传对应的接口

@csrf_exempt  #让post的时候免除csrf
@xframe_options_sameorigin #也是让post的时候
def uploadimg_kindeditor(request):
    unique_id = uuid.uuid4()
    surfix = os.path.splitext(request.FILES['imgFile'].name)[-1] #拿到文件后缀的方法splitext
    filename = str(unique_id) + surfix
    dir = "%s/upload/comments/imgs/"+filename
    result = {"error": 0,"url": dir%'/static','message':'123'} #页面上 用static别名访问
    try:
        with open(dir%'./statics', 'wb') as file: #保存时,用真实的statics路径,前面加‘.’才是相对于项目的根目录
            for chunk in request.FILES['imgFile'].chunks(): # 保存在内存的文件,需要chunks()一块一块地写入
                file.write(chunk)
    except Exception as e:
        print(e)
        result = {"error": 1, "url": dir, 'message': '图片上传失败'}
    return HttpResponse(json.dumps(result))

引入kindeditor相关问题

一、kindeditor上传图片时,csrf限制 加{csrf token}也不行。要注释掉setting.py那行才行。
    不知道正确的解决方法。
    https://blog.csdn.net/weixin_41782332/article/details/81140172
    @csrf_exempt 在对应视图函数加上这个装饰器来解决
    
    但按照格式返回响应,浏览器还是没有能够接受
    Refused to display 'http://127.0.0.1:8000/' in a frame because it set 'X-Frame-Options' to 'deny'.
    https://www.cnblogs.com/lph970417/p/12896689.html
    @xframe_options_sameorigin 再添加这个装饰器就可以了


二、保存图片的方法https://blog.csdn.net/xun527/article/details/132763904
@xframe_options_sameorigin
def uploadimg_kindeditor(request):
    print(request.FILES)
    result = {"error": 0,"url": "/static/imgs/5454545.png",'message':'123'}
    with open("/imgs/ma.png", 'wb') as file:
        for chunk in request.FILES['imgFile'].chunks():
            file.write(chunk)
        print('123')
    return HttpResponse(json.dumps(result))

总是报 没有对应文件路径的错误

是路径不对:
with open('/t.txt','w') as f:
	f.write("123"
这样会在系统根目录创建并写入!!!!

with open('./imgs/t.txt','w') as f:
	f.write("123")
这样才是在项目根目录

腾讯地图js

<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
<script>
window.onload = function(){
		//直接加载地图
    //初始化地图函数  自定义函数名init
    function init() {
        var center = new qq.maps.LatLng(22.914751,114.083267);      // 地图的中心地理坐标。
        //定义map变量 调用 qq.maps.Map() 构造函数   获取地图显示容器
         var map = new qq.maps.Map(document.getElementById("container"), {
            center: center,
            zoom:11                                                 // 地图的中心地理坐标。
        });
        var marker = new qq.maps.Marker({  // 标记
            position: center,
            map: map
        })
    }

    //调用初始化函数地图
    init();
}
</script>
<!--   定义地图显示容器   -->
<div id="container">
    <div>
      #其它是复制指南的代码。这里自己添加一个a标签,点击跳转到腾讯地图页,并指定了初识位置
        <a target="_blank" href="http://apis.map.qq.com/uri/v1/marker?marker=coord:28.914751,106.083267;title:**市***镇;addr:**大厦" style="position: fixed; z-index: 100"><i class="itag"></i>查看完整地图</a>  {# z-index:100使不被遮盖,前提position不是static。 i标签 加个样式 显示图标 #}
    </div>
</div>

Highchart

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="https://cdn.hcharts.cn/jquery/jquery-1.8.3.min.js"></script>
    <script src="https://cdn.hcharts.cn/highcharts/highcharts.js"></script>
</head>
<body>
<div id="container"></div>
<script>
    Highcharts.setOptions({
        global: {
            useUTC: false
        }
    });
    $(function(){
        initChart();
    })
    
    function initChart(){
        var config = {
            chart: {
                type: 'spline'
            },
            title: {
                text: '动态模拟实时数据'
            },
            xAxis: {
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: '值'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function () {
                    return '<b>' + this.series.name + '</b><br/>' +
                            Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
                            Highcharts.numberFormat(this.y, 2);
                }
            },
            legend: {
                enabled: true
            },
            exporting: {
                enabled: false
            },
            series: [
                {
                    name: 'A',
                    data: [
                        [1491535949788.035, 7.0],
                        [1491535949888.035, 6.0],
                        [1491535949988.035, 10.0],
                        [1491535950088.035, 1.0],
                    ]
                },
                {
                    name: 'B',
                    data: [
                        [1491535949788.035, 8.0],
                        [1491535949888.035, 2.0],
                        [1491535949988.035, 40.0],
                        [1491535950088.035, 1.0],
                    ]
                }
                ,
                {
                    name: 'C',
                    data: [
                        [1491535949788.035, 10.0],
                        [1491535949888.035, 2.0],
                        [1491535949988.035, 10.0],
                        [1491535950088.035, 8.0],
                    ]
                }
                
            ]
        };
        // 数据库中获取 series
{#        $('#container').highcharts(config);#}
        $.ajax({
            url: '/backend/trouble-json-report.html',
            dataType: 'json',
            success:function(arg){
                config['series'] = arg;
                $('#container').highcharts(config);
            }
        })

    }
</script>
</body>
</html>
def trouble_report(request):
    return render(request,'backend_trouble_report.html')

def trouble_json_report(request):
    # 数据库中获取数据
    user_list = models.UserInfo.objects.filter()
    response = []
    for user in user_list: # ?????
        from django.db import connection, connections
        cursor = connection.cursor()
        cursor.execute("""select strftime('%%s',strftime("%%Y-%%m-01",ctime)) * 1000,count(id) from repository_trouble where processer_id = %s group by strftime("%%Y-%%m",ctime)""", [user.nid,])
        result = cursor.fetchall()
        print(user.username,result)
        temp = {
            'name': user.username,
            'data':result
        }
        response.append(temp)
    import json
    return HttpResponse(json.dumps(response))

Dropzone

Dropzone

<form id="myAwesomeDropzone"  action="{% url 'enrollment_fileupload' enrollment_obj.id %}" class="dropzone">
  <div class="fallback">
    <input name="file" type="file" multiple />
  </div>
</form>
<script src="/static/plugins/dropzone/dropzone.js"></script># 引入dropzone的js
    <script># 以下dropzone设置不太正确。查看自己的项目正确用法
        // "myAwesomeDropzone" is the camelized version of the HTML element's ID
        Dropzone.options.myAwesomeDropzone = {
          paramName: "file", // The name that will be used to transfer the file
          maxFilesize: 2, // MB
          maxFiles:2,
          parallelUploads:1,
          accept: function(file, done) {
            if (file.name == "justinbieber.jpg") {
              done("Naha, you don't.");
            }
            else { done(); }
          }
        };

        $(function() {
          // Now that the DOM is fully loaded, create the dropzone, and setup the
          // event listeners
          // Prevent Dropzone from auto discovering this element:
          Dropzone.options.myAwesomeDropzone = false;
          var myDropzone = new Dropzone("#myAwesomeDropzone");
          myDropzone.on("success", function(file,response) {
            /* Maybe display some more file information on your page */
             console.log("completet", file, response);
             var response = JSON.parse(response);
             if (!response.status){
                 alert(response.err_msg);
             }else {
                 $("#uploaded_files").append("<li>"+ file.name +"</li>");
             }
          });
        })
    </script>

个人使用

<script>
   $(function () {
     Dropzone.options.myAwesomeDropzone = false;
     var myDropzone = new Dropzone("#myAwesomeDropzone");
     myDropzone.on("success", function (file,response) {
       if (!JSON.parse(response).status){
         alert(response.err_msg);
       }else{
         $("#uploaded_files").append("<li>"+ file.name +"</li>");
       }
     });

     myDropzone.options.maxFiles = 2;
     myDropzone.options.maxFilesize = 2;
     {#            myDropzone.accept = function (file, done) {#}
      {#                console.log("accept", this.files);#}
      {#                done();#}
      {#            }#}
   })
   </script>
posted @   Bruce_JRZ  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示