Fork me on GitHub

WangEditor+thinkphp5【真实可用+原创】

今天公司要编辑文章,一开始准备用ueditor,但是到了linux环境下一直不行,所以最终放弃。改用另外一个编辑器WangEditor。更加轻量级。

遇到最大的问题是 一个是图片上传,一个是div中的选择器editor没有value和name,那么post过去的值就不会有这个属性。

解决问题和过程如下:

1.先把wangeditor放在public/static/js下面

2.然后再进入到编辑页面。

edit.html

{include file='public/head'}
<body>
    <style media="screen" type="text/css">
        header {
            color: black;
        }
    </style>
    <div class="x-body">
        <form action="edit" class="layui-form" id="mainForm" method="post" style="margin-right: 20px;" enctype="multipart/form-data">
            <input type="hidden" name='id' value="{$data.id}">
            <div class="layui-form-item">
                <label class="layui-form-label">文章标题</label>
                <div class="layui-input-block">
                    <input type="text" name="title" required  lay-verify="required" placeholder="请输入标题" value="{$data['title']}" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">文章分类</label>
                <div class="layui-input-block layui-btn-xs">
                    {foreach $category as $key=>$vo}
                    <input type="radio" name="cid" value="{$vo.id}" title="{$vo.name}" {if $data['cid'] eq $vo.id} checked{/if}>
                    {/foreach}
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">文章内容</label>
                <div class="layui-input-block">
                    <script src="__static__/js/wangEditor/wangEditor.min.js" type="text/javascript"></script>
                    <div id="editor">
                        {$data.content}
                    </div>
                    <textarea id="editor_content" name="content_x" style="display:none;"></textarea>
                    <script type="text/javascript">
                        var E = window.wangEditor
                        var editor = new E('#editor');
                        var editor_content = $('#editor_content');
                        // 或者 var editor = new E( document.getElementById('editor') )
                        editor.customConfig.uploadFileName = 'uploadfile';
                        editor.customConfig.uploadImgServer = '/index.php/admin/wangeditor/upload';  // 上传图片到服务器
                        editor.customConfig.onchange = function (html) {
                            // 监控变化,同步更新到 textarea
                            editor_content.val(html);
                         };
                        editor.create();


                    </script>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button style="margin-left: 20%" class="layui-btn" lay-submit="" lay-filter="toSubmit">提交</button>
                    <button id="reset" type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>

        </form>
    </div>
</body>
<script type="text/javascript">
    // $("#status").val(0);
    var form = layui.form;
    var layer = layui.layer;
              //自定义验证规则
              form.verify({
                password: function(value){
                  if(value.length < 3){
                    return '标题至少得2个字符啊';
                  }
                }
              });
        //监听提交
        form.on('submit(demo1)', function(data){
              layer.alert(JSON.stringify(data.field), {
              title: '最终的提交信息'
            })
            return false;
        });
    $(document).ready(function(){
        //var editorHtml = $('#editor').val();
        
               var options = {
              type:'post',           //post提交
              // url:'http://ask.tongzhuo100.com/server/****.php?='+Math.random(),   //url
              dataType:"json",        //json格式
              data:{},    //如果需要提交附加参数,视情况添加
              clearForm: false,        //成功提交后,清除所有表单元素的值
              resetForm: false,        //成功提交后,重置所有表单元素的值
              cache:false,          
              async:false,          //同步返回
              success:function(data){
                  console.log(data);
                  if(data.code==0){
                      layer.msg(data.msg);
                  }else{
                      layer.msg(data.msg,{icon:1,time:500},function(){
                          $("#reset").click();
                          x_admin_close();
                          parent.location.reload();
                      });
                  }
                //服务器端返回处理逻辑
              },
              error:function(XmlHttpRequest,textStatus,errorThrown){
                layer.msg('操作失败:服务器处理失败');
              }
            }; 

        // bind form using 'ajaxForm' 
        $('#mainForm').ajaxForm(options).submit(function(data){
            location.href="/index.php/admin/article/getArticleList";
        });
    });
</script>
{include file='public/foot'}

核心代码区块:

            <div class="layui-form-item">
                <label class="layui-form-label">文章内容</label>
                <div class="layui-input-block">
                    <script src="__static__/js/wangEditor/wangEditor.min.js" type="text/javascript"></script>
                    <div id="editor">
                        {$data.content}
                    </div>
                    <textarea id="editor_content" name="content_x" style="display:none;"></textarea>
                    <script type="text/javascript">
                        var E = window.wangEditor
                        var editor = new E('#editor');
                        var editor_content = $('#editor_content');
                        // 或者 var editor = new E( document.getElementById('editor') )
                        editor.customConfig.uploadFileName = 'uploadfile';
                        editor.customConfig.uploadImgServer = '/index.php/admin/wangeditor/upload';  // 上传图片到服务器
                        editor.customConfig.onchange = function (html) {
                            // 监控变化,同步更新到 textarea
                            editor_content.val(html);
                         };
                        editor.create();
                    </script>
                </div>
            </div>

然后请求的控制:

一个是图片的上传:Wangeditor

<?php
namespace app\admin\controller;

use think\Controller;

/**
 * wangEditor
 */
class Wangeditor extends Controller
{
    public function upload()
    {
        $file = request()->file('uploadfile');

        // 移动到框架应用根目录/public/uploads/ 目录下
        $data = [];
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($info) {
                $imgp = str_replace('\\','/',$info->getSaveName());

                $data = [
                    'errno' => 0,
                    'data' => !empty($info) ? ['/public/uploads/'.$imgp] : []
                ];

            } else {
                $data = [
                    'errno' => $file->getError(),
                    'data' => []
                ];

            }
        }

        return json_encode($data);
    }
}

一个是文章的编辑 Article.php

<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;

/**
 * 文章管理
 */
class Article extends Controller
{
    // 文章列表
    public function getArticleList()
    {
        $article = Db::name('article')
            ->alias('a')
            ->join('category c','c.id=a.cid')
            ->field('a.id as aid, a.*,c.*')
            ->order('a.id asc')
            ->paginate('15');

        $page = $article->render();
        $total = $article->total();

        $this->assign('article', $article);
        $this->assign('page', $page);
        $this->assign('count', $total);

        return $this->fetch('article_list');
    }

    // 編輯文章
    public function editArticle()
    {
        $id = (int)$this->request->get('id');
        $data = Db::name('article')->where('id', $id)->find();

        $category = Db::name('category')->select();
        return $this->fetch('edit', ['data' => $data, 'category' => $category]);
    }

    // 保存编辑之后的文章数据
    public function edit()
    {
        $post = $this->request->post();
        $post['content'] = $post['content_x'];
        unset($post['content_x']);

        $id = (int)$post['id'];
        unset($post['id']);

        Db::name('article')->where('id', $id)->update($post);
        $this->success('保存成功');
    }
}

 

这样就完美的实现了。

 

posted @ 2019-03-29 17:25  我曾如此奢望  阅读(1478)  评论(0编辑  收藏  举报