一个基于weui的表单添加页

 

 

1、公众号页面跳转规则:

    

/*

    * 公众号页面进入规则:

    * 1.先请求接口获得一个URL

    * 2.跳转请求的URL,腾讯会重定向到本地的页面

    * 3.解析重定向的页面,获取code

    * 4.传递code,获取到openid

    * 5.openid是微信的唯一标识,拿到之后就可以请求自己的后台了(获取绑定用户列表、解绑、绑定等)

    * */

 

2、上传附件的时候,是先上传保存到服务器拿到附件的id、src、name,直接根据sec显示,这里是转为base64显示的

/**
 * 上传附件
 * 1、先使用base64显示
 * 2、提交上传
 * 3.保存表单
 * */
function uploadAnyfilesFun() {
    var uploadFiles = document.querySelector('#upload_file');

    uploadFiles.addEventListener('change', function () {
        var file = this.files[0];

        // 图片上传后台

        let formData = new FormData();
        formData.append('file', file);
        $.ajax({
            url: baseUrl+'/wechat/opinion/upload',
            type: 'POST',
            traditional: true,
            headers: {'token': Sessiontoken},
            data: formData,
            processData: false,  //tell jQuery not to process the data
            contentType: false,  //tell jQuery not to set contentType
            success: function (data) {
                if (data.code != 0) {
                    $.toast("上传附件失败", 'forbidden')
                    return
                }else{
                    fileList.push(data.data)

                    //实例化fileReader,
                    let  fd = new FileReader();
                    //获取当前选择文件的类型
                    let fileType = file.type;
                    //调它的readAsDataURL并把原生File对象传给它,
                    fd.readAsDataURL(file);//base64

                    // base64显示图片
                    fd.onload = function(){
                        if(/^image\/[jpeg|png|jpg|gif]/.test(fileType)){
                            let s =  Date.parse(new Date())
                            let h = '<span>' +
                                '<img onclick="imgsAction(this,\''+data.data.id+'\')" src="'+this.result+'" alt="">' +
                                '</span>'
                            $(".imgsDemo").append(h)
                        }
                    }
                }
            }
        });


    }, false);
}

3、一个小知识点:数组中,根据索引删除数组中的元素

Array.prototype.delete=function(delIndex){
    var temArray=[];
    for(var i=0;i<this.length;i++){
        if(i!=delIndex){
            temArray.push(this[i]);
        }
    }
    return temArray;
}
// 删除保存的文件
let d = fileList.findIndex((item,index)=>{
    return item.id === s
})
fileList = fileList.delete(d)

4、完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>咨询建议</title>
</head>
<link rel="stylesheet" href="https://cdn.bootcss.com/weui/1.1.3/style/weui.min.css">
<link rel="stylesheet" href="https://cdn.bootcss.com/jquery-weui/1.2.1/css/jquery-weui.min.css">

<link rel="stylesheet" href="../../src/dist/css/page.css">

<body>
<div class="weui-cells user-binding">
    <div class="weui-cells__tips">咨询建议</div>
    <div class="weui-cell">
        <div class="weui-cell__hd">
            <i class="iconfont iconyonghuming"></i>
        </div>
        <div class="weui-cell__bd">
            <p>姓名</p>
        </div>

        <div class="weui-cell__bd">
            <input class="weui-input" type="text" placeholder="请输入姓名" id="username">
        </div>
        <div class="weui-cell__ft" style="position: absolute;right:10px;">
            <input type="checkbox" style="position: relative;top:2px;margin-right: 4px;" id="isAnonymity">匿名
        </div>
    </div>
    <div class="weui-cell">
        <div class="weui-cell__hd">
            <i class="iconfont icondianhua"></i>
        </div>
        <div class="weui-cell__bd">
            <p>电话</p>
        </div>

        <div class="weui-cell__bd">
            <input class="weui-input" type="text" placeholder="请输入您的联系电话" id="phone">
        </div>
    </div>
    <div class="weui-cell">
        <div class="weui-cell__hd">
            <i class="iconfont icondizhi"></i>
        </div>
        <div class="weui-cell__bd">
            <p>地址</p>
        </div>

        <div class="weui-cell__bd">
            <input class="weui-input" type="text"  placeholder="请输入您的详细地址" id="address">
        </div>
    </div>
    <div class="weui-cell">
        <div class="weui-cell__hd">
            <i class="iconfont iconSpare"></i>
        </div>
        <div class="weui-cell__bd">
            <p>反映事项</p>
        </div>

        <div class="weui-cell__bd">
            <input class="weui-input" type="text"  placeholder="请选择反映事项" id="type">
        </div>
    </div>
    <div class="weui-cell">
        <div class="weui-cell__hd">
            <i class="iconfont iconleixing"></i>
        </div>
        <div class="weui-cell__bd">
            <p>事项详情</p>
        </div>
        <div class="weui-cell__bd">
            <textarea class="weui-textarea" placeholder="请输入事项详情" rows="3" id="eventdetail"></textarea>
        </div>
    </div>
    <div class="weui-cell">
        <div class="weui-cell__hd">
            <i class="iconfont icontec"></i>
        </div>
        <div class="weui-cell__bd">
            <p>上传图片</p>
        </div>
        <div class="weui-cell__bd">
            <div class="weui-cell__ft add-cell" onclick="uploadAnyfiles.uploadFilesFun()">+ 上传</div>
        </div>
    </div>
    <div class="weui-cell">
        <div class="imgsDemo"></div>
    </div>

    <div class="button_sp_area">
        <a href="javascript:;" class="weui-btn weui-btn_primary" onclick="doAction()">提交</a>
    </div>
</div>
<div class="showImgDemo">
    <img src="https://pic4.zhimg.com/50/v2-f171216c639bef831d765b41c359af4c_hd.jpg" alt="" onclick="hideBigImg()">
</div>
<div class="select_file" style="display: none;">
    <input type="file" accept="image/*" id="upload_file" capture="camera">
</div>

<script src="https://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/jquery-weui/1.2.1/js/jquery-weui.min.js"></script>

<!-- Dist -->
<script src="../../src/dist/js/index.js"></script>
<script src="../../src/dist/js/utils.js"></script>
<script src="../../src/dist/js/request.js"></script>
<script src="../../src/dist/js/uploadAnyfiles.js"></script>
<script>
    var wcode = '',
        openid = '';
    var customid = '';
    var fileList = [];
    const typeOption = [
        {
            title: "咨询",
            value: "1",
        },
        {
            title: "投诉",
            value: "2",
        },
        {
            title: "表扬",
            value: "3",
        }
    ]

    $(function(){
        var paras = location.search;            //search获得地址中的参数,内容为'?itemId=12'
        var result = paras.match(/[^\?&]*=[^&]*/g);     //match是字符串中符合的字段一个一个取出来,result中的值为['login=xx','table=admin']
        paras = {};                    //让paras变成没有内容的json对象
        for (i in result) {
            var temp = result[i].split('=');    //split()将一个字符串分解成一个数组,两次遍历result中的值分别为['itemId','xx']
            paras[temp[0]] = temp[1];
        }
        let code = paras.code;     //根据参数名"itemId",获取参数值

        console.log(code)

        loadCsConter()
        return
        if(code){
            wcode = code
            getOpenId()
        }else{
            getWeiXinURL()
        }

        loadCsConter()
    })

    function loadCsConter() {
        $("#type").select({
            title: "反映事项",
            items: typeOption
        });

        uploadAnyfilesFun()
    }

    /**
     * 上传附件
     * 1、先使用base64显示
     * 2、提交上传
     * 3.保存表单
     * */
    function uploadAnyfilesFun() {
        var uploadFiles = document.querySelector('#upload_file');

        uploadFiles.addEventListener('change', function () {
            var file = this.files[0];

            // 图片上传后台

            let formData = new FormData();
            formData.append('file', file);
            $.ajax({
                url: baseUrl+'/wechat/opinion/upload',
                type: 'POST',
                traditional: true,
                headers: {'token': Sessiontoken},
                data: formData,
                processData: false,  //tell jQuery not to process the data
                contentType: false,  //tell jQuery not to set contentType
                success: function (data) {
                    if (data.code != 0) {
                        $.toast("上传附件失败", 'forbidden')
                        return
                    }else{
                        fileList.push(data.data)

                        //实例化fileReader,
                        let  fd = new FileReader();
                        //获取当前选择文件的类型
                        let fileType = file.type;
                        //调它的readAsDataURL并把原生File对象传给它,
                        fd.readAsDataURL(file);//base64

                        // base64显示图片
                        fd.onload = function(){
                            if(/^image\/[jpeg|png|jpg|gif]/.test(fileType)){
                                let s =  Date.parse(new Date())
                                let h = '<span>' +
                                    '<img onclick="imgsAction(this,\''+data.data.id+'\')" src="'+this.result+'" alt="">' +
                                    '</span>'
                                $(".imgsDemo").append(h)
                            }
                        }
                    }
                }
            });


        }, false);
    }

    // 获取openid,之后才能进行添加操作
    function getOpenId() {
        get("/wechat/binding/toIdentityBinding?code="+wcode, {}, function (data) {
            if (data.code === 0) {
                openid = data.data

            } else {
                $.toast('获取openid失败!', 'forbidden');
            }
        }, false, true);
    }

    //获取URL
    function getWeiXinURL() {
        get("/wechat/binding/getAuthUrl", {}, function (data) {
            if (data.code === 0) {
                let url = data.data
                url='https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri=http://zbcsrq.com:33813/pages/ConsultationAdvice/add.html&appid=wx60c25e54627b700d&response_type=code&scope=snsapi_base&state=#wechat_redirect'
                location.replace(url)
            } else {
                $.toast('获取URL失败!', 'forbidden');
            }
        }, false, true);
    }

    function hideBigImg() {
        $(".showImgDemo").hide()
    }

    function isPoneAvailable(poneInput) {
        var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
        if (!myreg.test(poneInput)) {
            return false;
        } else {
            return true;
        }
    }
    // 点击图片操作“
    function imgsAction(obj,s) {
        $.actions({
            actions: [{
                text: "删除图片",
                onClick: function () {
                    //调用删除图片接口,删除上传到服务器的图片 ==== 待定
                    $(obj).parent().remove()
                    // 删除保存的文件
                    let d = fileList.findIndex((item,index)=>{
                        return item.id === s
                    })
                    fileList = fileList.delete(d)

                }
            },{
                text: "查看大图",
                onClick: function () {
                    //do something
                    let src = $(obj).attr("src")
                    $(".showImgDemo img").attr("src",src)
                    $(".showImgDemo").show()
                }
            }]
        });
    }
    Array.prototype.delete=function(delIndex){
        var temArray=[];
        for(var i=0;i<this.length;i++){
            if(i!=delIndex){
                temArray.push(this[i]);
            }
        }
        return temArray;
    }
    function doAction(){
        let username = $("#username").val()
        let phone = $("#phone").val()
        let type=$("#type").val()
        let address=$("#address").val()
        let content=$("#eventdetail").val()

        let isAnonymity = $("#isAnonymity").prop("checked")
        if(!isAnonymity && username===''){
            $.toast("非匿名时请填写姓名", "text")
            return
        }
        if(phone === ''){
            $.toast("请输入联系电话", "text")
            return
        }
        if(!isPoneAvailable(phone)){
            $.toast("联系电话格式不正确", "text")
            return
        }
        if(type === ''){
            $.toast("请选择反映事项", "text")
            return
        }
        let opiniontype = typeOption.find((i,v)=>{
            if(v.title = type)return v.value
        })

        let saveDataForm = {
            openid:openid,
            name:username,
            phone,
            address,
            content,
            opiniontype,
            fileList:fileList
        }


        post('/wechat/opinion', JSON.stringify(saveDataForm), function (data) {
            if (data.code != 0) {
                $.toast(data.msg, 'forbidden')
                return
            }else{
                $.toast("保存成功", 'text')
                setTimeout(function () {
                    location=location
                },1000*2)
            }
        }, false, true);

    }
    //上传附件
    function clickfile() {
        $("#file").click()
    }
</script>
</body>
</html>
完整代码

 

posted @ 2020-03-12 10:11  庞某人  阅读(1588)  评论(0编辑  收藏  举报