【JS】计算时间之间的日期

Continue Read..
var endTime = $("#end_date_time").val();//2018-07-20 03:30
endTime = Math.floor(new Date(endTime + ':00').getTime() / 1000);

var nTime = endTime - startTime;
var days =Math.floor(nTime/(24 * 3600));

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【微信小程序】web-view

Continue Read..

微信小程序直接用

<!-- wxml -->

<!-- 指向微信公众平台首页的web-view -->

<web-view src="https://url.com"></web-view>

 

这里面的url的head里面需要加

 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

<meta name="renderer" content="webkit">

<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">

 

不然字体会变很小

 

<style>

        .tui-editor-contents img{

            max-width: 100%; !important;

        }

    </style>

 

加这个会让图片铺平

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【tui.editor】使用和修改上传

Continue Read..

 

首先调用这些js css(有些是不需要的,自己删)

 <link href="http://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

<script src="http://cdn.bootcss.com/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>

<script>window.jQuery || document.write('<script src="/sta/dist/js/tui-editor/js/jquery-1.11.0.min.js"><\/script>')</script>

<script src="/sta/dist/js/tui-editor/lib/markdown-it/dist/markdown-it.js"></script>

<script src="/sta/dist/js/tui-editor/lib/toMark/dist/toMark.js"></script>

<script src="/sta/dist/js/tui-editor/lib/tui-code-snippet/dist/tui-code-snippet.js"></script>

<script src="/sta/dist/js/tui-editor/lib/tui-color-picker/dist/tui-color-picker.js"></script>

<script src="/sta/dist/js/tui-editor/lib/codemirror/lib/codemirror.js"></script>

<script src="/sta/dist/js/tui-editor/lib/highlightjs/highlight.pack.js"></script>

<script src="/sta/dist/js/tui-editor/lib/squire-rte/build/squire-raw.js"></script>

<link rel="stylesheet" href="/sta/dist/js/tui-editor/lib/codemirror/lib/codemirror.css">

<link rel="stylesheet" href="/sta/dist/js/tui-editor/lib/highlightjs/styles/github.css">

 

<script src="/sta/dist/js/tui-editor/lib/plantuml-encoder/dist/plantuml-encoder.js"></script>

<script src="/sta/dist/js/tui-editor/lib/raphael/raphael.js"></script>

<script src="/sta/dist/js/tui-editor/lib/tui-chart/dist/tui-chart.js"></script>

<script src="/sta/dist/js/tui-editor/dist/tui-editor-Editor-all.js"></script>

<link rel="stylesheet" href="/sta/dist/js/tui-editor/dist/tui-editor.css">

<link rel="stylesheet" href="/sta/dist/js/tui-editor/dist/tui-editor-contents.css">

<link rel="stylesheet" href="/sta/dist/js/tui-editor/lib/tui-color-picker/dist/tui-color-picker.css">

<link rel="stylesheet" href="/sta/dist/js/tui-editor/lib/tui-chart/dist/tui-chart.css">

 

 

我的表单是用from 提交的,大家也可以直接ajax提交表单

 

<form action="/article/<?=$this->ectType?>/" id="id-form" class="form-horizontal form-validate" role="form"

                  method="post" onsubmit="return subF();">

  

                <div class="align-left">

 

                    <div class="form-group">

                        <label class="col-xs-2 control-label no-padding-right">内容</label>

                        <div class="col-xs-9" id="contentEditor"></div>

                        <textarea type="text"  hidden name="content" id="content" class="col-xs-6" rows="6"> </textarea>

                    </div>

     

                </div>

                <div class="clearfix form-actions">

                    <div class="col-md-offset-2 col-md-9">

                        <button class="btn btn-info" type="submit">

                            <i class="ace-icon fa fa-check bigger-110"></i>

                            提交

                        </button>

                    </div>

                </div>

            </form>

 

 

    <script class="code-js">

        var content = [];

        //这里需要注意,php需要传一个json对象过来,

        //$data['content'] = explode("\r\n", $data['content']);

        //$data['content'] = json_encode($data['content']);

 

        content = <?= $this->data['content']; ?>;

        

        //var content = [

        //    '| @cols=2:merged |',

        //    '| --- | --- |',

        //    '| table | table |',

        //    '```uml',

        //    'partition Conductor {',

        //    '  (*) --> "Climbs on Platform"',

        //    '  --> === S1 ===',

        //    '  --> Bows',

        //    '}',

        //    '',

        //    'partition Audience #LightSkyBlue {',

        //    '  === S1 === --> Applauds',

        //    '}',

        //    '',

        //    'partition Conductor {',

        //    '  Bows --> === S2 ===',

        //    '  --> WavesArmes',

        //    '  Applauds --> === S2 ===',

        //    '}',

        //    '',

        //    'partition Orchestra #CCCCEE {',

        //    '  WavesArmes --> Introduction',

        //    '  --> "Play music"',

        //    '}',

        //    '```',

        //    '```chart',

        //    ',category1,category2',

        //    'Jan,21,23',

        //    'Feb,31,17',

        //    '',

        //    'type: column',

        //    'title: Monthly Revenue',

        //    'x.title: Amount',

        //    'y.title: Month',

        //    'y.min: 1',

        //    'y.max: 40',

        //    'y.suffix: $'

        //].join('\n');

 

        var editor = new tui.Editor({

            el: document.querySelector('#contentEditor'),

            previewStyle: 'vertical',

            height: '300px',

            initialEditType: 'wysiwyg',

            useCommandShortcut: true,

            initialValue: content.join('\n'),

            hooks: {

                addImageBlobHook: addImageBlobHook.bind(this),

            },

            exts: ['scrollSync', 'colorSyntax', 'uml', 'chart', 'mark', 'table', 'taskCounter']

        });

        console.log(editor);

 

        function addImageBlobHook(blob, callback) {

 

            const data = new FormData();

            //blob就是一个文件对象

 

点击查看原图

            data.append('upfile', blob);

            //console.log(data, $('#cuzn123')[0]);

 

         //console.log 打印data的时候确实为空,要用下面的方法打印,然后看php获取的值,之前一直用get,拿不到值,换了post就好了

            //console.log(data.has("upfile"));//true

            console.log(data.get("upfile"));

            //data.forEach(function(file){

            //    console.log(file);

            //});

            

            $.ajax({

                url: "/index/upToQiniu/",

                type: "POST",

                data: data,

                //dataType: 'JSON',

                processData: false,

                contentType: false,

                //async: false,

                cache: false,

                //headers: {

                //    'Content-Type': 'multipart/form-data'

                //},

                success: function (result) {

                    result = JSON.parse(result);

                    console.log(typeof result);

                    console.log("result['state'] : " + result["state"]);

                    console.log("result.state : " + result.state);

                    if (result["state"] == 'SUCCESS') {

                        //这里是生成htpp模式的图片地址(我这里是七牛返回的一个key,需要转换)

                        var image = MyCommon.getViewImage(result["key"]);

                        //这里是插件自带的回调函数

                        callback(image, 'alt text');

                    }

                    console.log(result);

                },

                error: function (e) {

                    console.log(e);

                }

            });

            //$.get('/upload-images', data, config) .then(response => { callback(response.data.url, ''); }) .catch(error => { })

        }

        

        //提交表单之前 把值插入textarea 里面

        function subF() {

            $("#content").val(editor.getMarkdown ());

            //console.log('editor.getHtml () : ' + editor.getHtml ());

            //console.log('editor.getValue () : ' + editor.getValue ());

            //console.log('editor.getMarkdown () : ' + editor.getMarkdown ());

            return true;

        }

    </script>

 

 try {

$ret = QiNiu::upload($_FILES["upfile"]["tmp_name"]);

$result = [

'state' => 'SUCCESS',

'key' => $ret,

];

} catch (Exception $e) {

$result = [

'state' => $e->getMessage(),

];

}

echo json_encode($result);

 

 

最后要显示数据库的值需要用Markdown转HTML的插件 showdown

 点击查看原图

<script src="/sta/dist/js/showdown-1.8.6/dist/showdown.js"></script>

<div class="row">

    <div class="col-xs-12" id="content">

    </div>

</div>

 

<!--js:start-->

<script>

 

    //这里的php只需要 $data['content'] = json_encode($data['content']);

 

    var content = '';

    <?php  if (!empty($this->data['content'])) { ?>

    content = <?= $this->data['content']; ?>;

    <?php } ?>

    var converter = new showdown.Converter({

            "omitExtraWLInCodeBlocks":true,

            "noHeaderId":false,

            "prefixHeaderId":"",

            "ghCompatibleHeaderId":true,

            "headerLevelStart":1,

            "parseImgDimensions":true,

            "simplifiedAutoLink":true,

            "excludeTrailingPunctuationFromURLs":false,

            "literalMidWordUnderscores":true,

            "strikethrough":true,

            "tables":true,

            "tablesHeaderId":false,

            "ghCodeBlocks":true,

            "tasklists":true,

            "smoothLivePreview":true,

            "smartIndentationFix":false,

            "disableForced4SpacesIndentedSublists":false,

            "simpleLineBreaks":false,

            "requireSpaceBeforeHeadingText":false,

            "ghMentions":false,"extensions":[],"sanitize":false

        }),

        //text = '# hello, markdown!',

        html = converter.makeHtml(content);

    $("#content").html(html);

</script>

<!--js:end-->

 点击查看原图

 

参考网站

https://qiita.com/dala00/items/93f96dfbf63e71765562  这个是addImageBlobHook使用的,整个google就这个日本鬼子写了这个

 

这个是官方的文档,硬是想打死这个作者

https://nhnent.github.io/tui.editor/api/latest/ToastUIEditor.html#getHtml  

https://github.com/nhnent/tui.editor#-examples

 

showdown 参考网址

https://github.com/showdownjs/showdown

https://blog.csdn.net/yzf913214/article/details/54607897 

 

 

tui-editor.zip showdown-1.8.6.zip

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【PHP】mysql嵌套事物

Continue Read..

公司的一个项目需要在一个函数里面的调用多个函数,但是每个函数都用到了mysql事物,按照原生的mysql事物,只有一层

也就是说 A函数包含了B函数,如果B函数事物成功,A再没有commit的时候也能提交事物,这样就不对了

 

直接上代码

 

写一个class

定义一个静态变量

//事物laravel

static private $transactions = 0;

 

public function begin() {
        ++self::$transactions;
        if (self::$transactions == 1) {
            $sql = 'BEGIN';
            $conn = $this->getMasterConn();
            
            return DBMysqli::execute($conn, $sql);
        }
	}

	/**
	 * 提交事务
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function commit() {
        if (self::$transactions == 1) {
            $sql = 'COMMIT';
            $conn = $this->getMasterConn();
            
            return DBMysqli::execute($conn, $sql);
        }
        --self::$transactions;
	}

	/**
	 * 回滚事务
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function rollback() {
        if (self::$transactions == 1) {
            self::$transactions = 0;
            $sql = 'ROLLBACK';
            $conn = $this->getMasterConn();
    
            return DBMysqli::execute($conn, $sql);
        } else {
            --self::$transactions;
        }
	}

参考网站 https://blog.csdn.net/hello_katty/article/details/45220825

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【js】数字转汉字

Continue Read..
function DX(n) {
    if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))
        return "数据非法";
    var unit = "千百拾亿千百拾万千百拾元角分", str = "";
    n += "00";
    var p = n.indexOf('.');
    if (p >= 0)
        n = n.substring(0, p) + n.substr(p+1, 2);
    unit = unit.substr(unit.length - n.length);
    for (var i=0; i < n.length; i++)
        str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
    return str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整");
}

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【docker】用docker搭lnmrp环境

Continue Read..

l=>linux

n=>nginx

m=>mysql (主从)

r=>redis(临时主从,永久主从)

p=>php

 

1、准备

 

1.1、安装vagrant、VirtualBox

 

附件地址 https://pan.baidu.com/s/1jKgUSpK 

 

1.2、在D盘创建cuzn目录,把Vagrantfile、docker和box拷贝到D:/cuzn/下,再创建目录D:/cuzn/data/etc和D:/cuzn/data/www

 

 

 

2、用vagrant启动linux:

 

2.1、打开主机命令行窗口(cmd.exe),并进入到当前目录下

D:

cd cuzn

 

2.2、初始化vagrant并启动linux:

#vagrant box add inviqa/centos-7-minimal

vagrant up

 

2.3、登入linux

vagrant ssh

 

2.4、在linux中运行,并退出:

sudo yum -y update && yum -y install kernel-headers kernel-devel

exit

 

2.5、在主机安装vagrant插件,并重启

vagrant plugin install vagrant-vbguest

vagrant reload

 

2.6、使用SecureCRT登入linux

主机:127.0.0.1

端口:2218 (从Vagrantfile中查看)

用户名:root

密码:vagrant

 

 

 

3、linux 设置

 

3.1、中文支持

yum -y update

yum -y install kde-l10n-Chinese && yum -y reinstall glibc-common

localedef -c -f UTF-8 -i zh_CN zh_CN.utf8

 

vi /etc/locale.conf 

修改为:

LANG="zh_CN.UTF-8"

LANGUAGE="zh_CN:zh"

保存

 

3.2、修改时区:

查看(看时间和时区对不对,时区要为+0800):

date -R; date +%z

 

修改时区:

rm -f /etc/localtime 

cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 

 

如果时间不对,可以修改系统日期时间(假设15:48:00 2017-12-16是当前时间)

date -s '15:48:00 2017-12-16'

hwclock --set --date '15:48:00 2017-12-16'

hwclock --hctosys 

clock -w 

 

重启vagrant:

vagrant reload

 

3.3、linux基础工具

yum install -y net-tools lrzsz 

 

3.4、安全加强

yum install -y glibc glibc-common glibc-devel glibc-headers nscd \

bind-libs bind-libs-lite bind-license bind-utils \

gnutls tomcat-servlet-3.0-api wget \

kernel kernel-devel kernel-headers kernel-tools kernel-tools-libs python-perf \

python-perf \

libnl3 libnl3-cli NetworkManager NetworkManager-glib NetworkManager-tui \

libxml2 libxml2-python \

vim-common vim-enhanced vim-filesystem vim-minimal \

libtiff \

openssh openssh-clients openssh-server openssl-devel openssl-libs openssl-perl openssl-static \

libgcrypt libgcrypt-devel \

sqlite \

cups-filters cups-filters-libs \

ntp ntpdate \

libuser \

sssd-client \

subversion subversion-libs \

ModemManager-glib \

libpng \

openssl openssl-libs \

poppler poppler-utils \

abrt abrt-addon-ccpp abrt-addon-kerneloops abrt-addon-pstoreoops abrt-addon-python abrt-addon-vmcore abrt-addon-xorg abrt-cli abrt-console-notification abrt-libs abrt-python abrt-tui \

libreport libreport-cli libreport-filesystem libreport-plugin-mailx libreport-plugin-rhtsupport libreport-plugin-ureport libreport-python libreport-rhel libreport-web \

chrony \

openldap \

expat \

libXfont \

curl libcurl \

openssl098e \

nss nss-sysinit nss-tools nss-util \

git perl-Git \

pcre pcre-devel \

libxml2 libxml2-devel libxml2-python

 

rm -f /etc/cron.deny 

rm -f /etc/at.deny 

touch /etc/cron.allow 

touch /etc/at.allow 

chmod 0600 /etc/cron.allow 

chmod 0600 /etc/at.allow

 

 

 

4、安装docker

yum install -y yum-utils device-mapper-persistent-data lvm2

yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

yum install -y docker-ce-17.09.1.ce

systemctl start docker

systemctl enable docker

 

4.1、使用阿里云加速Docker

首先注册一个阿里云的帐号

进入:https://cr.console.aliyun.com/#/accelerator

根据提示,创建:/etc/docker/daemon.json

sudo systemctl daemon-reload

sudo systemctl restart docker

 

 

5、安装mysql

 

5.1、创建docker image

cd /docker/mysql/cuzn-mysql

./build.sh

 

5.1、安装主库

cd /docker/mysql

./run_master.sh 

注:123456是数据库root密码

 

5.2、安装从库

cd /docker/mysql

./run_slave.sh 3322

 

5.3重新弄mysql 从库

1.docker ps 找到从库的名称 mysql-slave-3322 

2.docker stop  mysql-slave-3322

3.docker rm  mysql-slave-3322

4.cd /data1/mysql

5.rm -rf rm -rf mysql-slave-3322/

6.cd /docker/mysql

7../run_slave.sh 3322

 

6、安装redis

 

6.1、安装缓存用的redis

cd /docker/redis/cuzn-redis

./build.sh

 

6.1.1、安装主库

cd /docker/redis/redis-cache-master-6480

./run.sh

 

6.1.2、安装从库

cd /docker/redis/cuzn-redis

./build.sh

cd /docker/redis/redis-slave

./run.sh redis-cache-master-6480 6481

 

6.2、安装永欠存储用的redis

 

6.2.1、安装主库

cd /docker/redis/redis-permanent-master-6490

./run.sh

 

6.2.2、安装从库

cd /docker/redis/redis-slave

./run.sh redis-permanent-master-6490 6491

 

6.3、管理工具:RedisDesktopManager

 

6.3.1、windows: 

https://redisdesktop.com/download

 

6.3.2、mac:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null ; brew install caskroom/cask/brew-cask 2> /dev/null

brew cask install rdm

 

 

 

7、安装git

yum -y install curl curl-devel zlib-devel openssl-devel perl cpio expat-devel gettext-devel

yum -y install git

 

7.1、设置简写

git config --system alias.st status

git config --system alias.ci "commit -m"

git config --system alias.co checkout

git config --system alias.br  branch

git config --system alias.mg  "merge --no-ff"

 

7.2、设置用户

 

git config --global user.name "你的姓名"

git config --global user.email "你的@邮箱.com"

 

7.3、设置 ssh key

cd 

rm -fr .ssh

ssh-keygen -t rsa -C "你的@邮箱.com"

一路回车

cat /root/.ssh/id_rsa.pub

复制内容备用

 

7.4、注册gitlab,并设置 ssh key

http://127.0.0.1:10011/

用“你的@邮箱.com”注册后进入:

http://127.0.0.1:10011/profile/keys

设置 ssh key,把8.3生成的id_rsa.pub内容填入

 

7.5、git工具:sourcetree,小乌龟(tortoisegit)

 

8、安装php和nginx

 

8.1、创建linux基础docker image

cd /docker/centos-systemd

./build.sh

 

8.2、创建php-nginx的docker image

cd /docker/php-nginx

./build.sh

 

8.3、创建数据

 

8.3.1、把nginx配置文件放到 D:/cuzn/data/etc 下

 

8.3.2 拉取网站数据

cd /data/www/

git clone ssh://git@127.0.0.1:12122/cuzn/cuzn.git

cd cuzn

git checkout develop

git pull develop

 

8.3.3 创建配置文件

cd conf

ln -s debug local

 

8.3.4 创建cache目录

cd ..

mkdir cache

chmod 777 cache

 

8.4、启动php-nginx

cd /docker/php-nginx

./run dev

 

 

 

9、设置host

如果是非线上环境,要设置host

 

9.1、下载host切换软件:switch host

 

9.2、查看服务器环境ip

ifconfig

 

9.3、设置host并切换到指定环境

 

 

 

9、安装supervisord

mkdir -p /data/etc/supervisord

mkdir -p /data2/logs/supervisord

chmod -R 777 /data2/logs/supervisord

yum install -y iproute python-setuptools hostname inotify-tools yum-utils which jq

yum clean all

rm -rf /var/cache/yum

easy_install supervisor

echo_supervisord_conf > /etc/supervisord.conf

sed -i "s|logfile=\/tmp\/supervisord\.log|logfile=\/data2\/logs\/supervisord\/supervisord\.log|g" /etc/supervisord.conf

sed -i "s|;\[include\]|\[include\]|g" /etc/supervisord.conf

sed -i "s|;files = relative\/directory\/\*\.ini|files = \/data\/etc\/supervisord\/\*\.ini|g" /etc/supervisord.conf

 

(cat <<EOF

[Unit]

Description=Supervisor daemon

 

[Service]

Type=forking

ExecStart=/usr/bin/supervisord

ExecStop=/usr/bin/supervisorctl $OPTIONS shutdown

ExecReload=/usr/bin/supervisorctl $OPTIONS reload

KillMode=process

Restart=on-failure

RestartSec=42s

 

[Install]

WantedBy=multi-user.target

EOF

) >/usr/lib/systemd/system/supervisord.service

 

systemctl enable supervisord.service

systemctl start supervisord.service

 

 

 

 

 

 

 

 

 

 

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【vagrant】配置centos环境,本地写代码,虚拟机测试

Continue Read..

用vagrant的好处,不用打开vbox的软件,就可以直接运行虚拟机,占用的内存资源小,可以各种配置和复制等

首先安装vagrant

https://www.vagrantup.com/downloads.html

然后下载需要的系统盘 ,我这里是centos72  https://app.vagrantup.com/boxes/search

然后安装vbox

https://www.vinchin.com/software/vm-backup-software-download.html

这里可以装破解汉化版(大家自己百度吧)

装好了之后

在D盘新建一个 centos72的文件夹

然后cmd进入这个文件夹

vagrant box add title url

title 是创建虚拟机的别名 我这里叫 centos72 

url   是刚才下载的centos72系统的本地路径 也可以是网络路径(建议使用本地的)

 

运行完不报错之后 

vagrant init centos72  

这里是安装这个环境到虚拟机

vagrant up 

启动虚拟机

 

d:/centos72文件夹里面会生成一个配置文件 Vagrantfile

修改配置文件 已搞好的配置文件我会上传到附件

主要修改的配置

 config.vm.network "forwarded_port", guest: 22, host: 2221

 config.vm.network "public_network", type: "dhcp"

  config.vm.synced_folder "D:/php_daima/", "/www/php_daima", create:true, :mount_options=>['dmode=777','fmode=777']

  config.vm.synced_folder "D:/centos72/nginx_conf", "/www/server/panel/vhost/nginx", create:true, :mount_options=>['dmode=777','fmode=777']

 

内存设置大点

vb.memory = "2048" 

 

配置文件已经写了 端口号是2221

直接用ssh工具链接 127.0.0.1:2221 账号 root 密码 vagrant (如果是在vagrant官方下载的系统就是这个密码)

 

安装环境 这里推荐 

https://lnmp.org/ (我装php7.1版本 和mysql 5.7版本的时候总是装不上)

https://www.bt.cn/bbs/thread-1186-1-1.html (我亲测的这个,php7.2 mysql5.7 装了N次才成功,ngxin1.12)

当然,有能力的直接装各个环境的官方版本或者docker

 

安装之后

因为配置文件里面已经共享了代码和配置的文件 直接启动就好了,这样就可以直接在一个纯净的win环境编写代码,直接在本地访问虚拟机(linux)的环境测试

 

切换host建议使用SwitchHosts

 

可能会出现本地修改了代码,虚拟机代码也显示改了,但是刷新页面的时候没生效

需要修改如下配置

ngxin.conf sendfile       off;

php.ini opcache.enable = 0

 

 

参考网址  http://blog.csdn.net/yjk13703623757/article/details/70040797

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【PHP】php 返回数组中指定多列的方法

Continue Read..
function array_columns($input, $column_keys=null, $index_key=null){ $result = array(); $keys =isset($column_keys)? explode(',', $column_keys) : array(); if($input){ foreach($input as $k=>$v){ // 指定返回列 if($keys){ $tmp = array(); foreach($keys as $key){ $tmp[$key] = $v[$key]; } }else{ $tmp = $v; } // 指定索引列 if(isset($index_key)){ $result[$v[$index_key]] = $tmp; }else{ $result[] = $tmp; } } } return $result; }

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【微信小程序】简单的表单提交

Continue Read..

HTML


table.html

<view>

<form bindsubmit="formSubmit" bindreset="formReset">
<view class="inputView" style="margin-top: 40% ">
<input type='text' name="name" placeholder="请输入姓名" ></input>
</view>
<view class="inputView">
<input type='text' name="password" password placeholder='请输入密码'></input>
</view>
<view class="inputView">
<input type='text' name="password1" password placeholder='请再次输入密码'></input>
</view>

<!-- 性别 -->
<view class="section">
<radio-group class="radio-group" bindchange="radioChange" name="r">
<label class="radio" wx:for="{{radioItems}}">
性别 :<radio value="{{item.name}}" checked="{{item.checked}}" />{{item.value}}
</label>
</radio-group>
</view>
<!-- 区域 -->
<view class="section">
<checkbox-group bindchange='checkboxChange' name="c">
区域 :
<label class='checkbox' wx:for='{{checkboxItems}}'>
<checkbox value='{{item.name}}' checked='{{item.checked}}'>{{item.value}}</checkbox>
</label>
</checkbox-group>
</view>

<!-- 上传图片 -->
<view class="section">
<button bindtap='upImg'>上传图片</button>
<input type='text' name="img" value="{{img}}"></input>
<image src="{{imgSrc}}" mode="aspectFit"></image>
</view>
<view class="btn-area">
<button formType="submit">Submit</button>
<button formType="reset">Reset</button>
</view>
</form>

</view>


JS

table.js

var app = require('../../resources/js/upload.js');
Page({
data: {
name:'',
password:'',
password1:'',
img:'',
imgStr:'',
radioItems: [
{ name: '1', value: '女' },
{ name: '2', value: '男', checked: 'true' }
],
checkboxItems:[
{mame:'1',value:'天门'},
{ name: '2', value: '仙桃', checked: 'true' },
{ name: '3', value: '潜江' }
]
},
formSubmit: function (e) {
var data = [];
data.name = e.detail.value.name;
if(data.name == ''){
wx.showModal({
title: '提示',
content: '请输入用户名',
showCancel: false
})
return;
}
data.password = e.detail.value.password;
if (data.password == '') {
wx.showModal({
title: '提示',
content: '请输入密码',
showCancel: false
})
return;
}
if (data.password != e.detail.value.password1) {
wx.showModal({
title: '提示',
content: '二次输入的密码不一致',
showCancel: false
})
return;
}
console.log(data);
console.log('form发生了submit事件,携带数据为:', e.detail.value)
},
formReset: function () {
console.log('form发生了reset事件')
},

upImg :function(){
var that = this;
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
that.setData({
imgSrc: res.tempFilePaths,
})
var imgdata = "";
imgdata = app.uploadImg(that, res.tempFilePaths);
}
})
}
})

upload.js



function uploadImg(page, path) {
wx.showToast({
icon: "loading",
title: "正在上传"
}),
wx.uploadFile({
url: 'http://xxx/testUpload.php',
filePath: path[0],
name: 'logo',
header: { "Content-Type": "multipart/form-data" },
formData: {
//和服务器约定的token, 一般也可以放在header中
'session_token': wx.getStorageSync('session_token')
},
success: function (res) {
console.log(res);
if (res.statusCode != 200) {
wx.showModal({
title: '提示',
content: '上传失败',
showCancel: false
})
return;
}
page.setData({ //上传成功修改显示头像
img: res.data,
})
},
fail: function (e) {
console.log(e);
wx.showModal({
title: '提示',
content: '上传失败',
showCancel: false
})
},
complete: function () {
wx.hideToast(); //隐藏Toast
}
})
}
module.exports.uploadImg = uploadImg; //这样暴露接口,这里不暴露是不能引用的

table.wxss
.input{
padding-left: 10px;
height: 44px;
}

.inputView{
border: 2px solid red;
border-radius: 40px;
margin-left: 15px;
margin-right: 15px;
margin-top: 15px;
}

php
//上传图片 $filename = 'logo'; $imgname = $_FILES[$filename]['name']; $tmp = $_FILES[$filename]['tmp_name']; $filepath = '/uploads/test/'; if(move_uploaded_file($tmp,'.'.$filepath.$imgname)){ echo $filepath.$imgname; }else{ echo "上传失败"; }

点击查看原图

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【微信小程序】多图片上传

Continue Read..

点击查看原图

 

 

HTML

 

<view class="picture_list">
<view wx:for="{{upload_picture_list}}" class="picture_item">
<image wx:if="{{item.upload_percent < 100}}" src="{{item.path}}" mode="aspectFill"></image>
<image wx:if="{{item.upload_percent == 100}}" src="{{item.path_server}}" mode="aspectFill"></image>
<view class="upload_progress" wx:if="{{item.upload_percent < 100}}">
{{item.upload_percent}}%
</view>
</view>
<view class="picture_item">
<image src="../../../resources/images/btn_uploadpic.png" bindtap="uploadpic" mode="aspectFill"></image>
</view>

</view>


CSS

.picture_list{
padding:20px;
display:flex;
flex-direction: row;
flex-wrap:wrap;
justify-content:flex-start;
align-items:flex-start;
align-content:flex-start;
}
.picture_item{margin:10px;position:relative;width:160rpx;height:160rpx;}
.upload_progress{position:absolute;top:0;left:0;opacity:0.7;background-color:#000;color:#fff;width:160rpx;height:160rpx;text-align:center;line-height:160rpx;font-size:12px;}
.picture_item image{width:160rpx;height:160rpx;}


js


var app = require('../../../resources/js/uploadimg.js');
Page({
data:{
upload_pictrue_list:[]
},
uploadpic : function (e){
var that = this;
var upload_picture_list = that.data.upload_pictrue_list;
wx.chooseImage({
count:9,
sizeType:['original','compressed'],
sourceType:['album','camera'],
success: function(res) {
//返回选定照片的本地文件路径,tempFilePath可以作为img标签的src属性
var tempFiles = res.tempFiles;
//循环把图片加入上传列表
for(var i in tempFiles){
tempFiles[i]['upload_percent'] = 0;
tempFiles[i]['path_server'] = "";
upload_picture_list.push(tempFiles[i]);
}
that.setData({
upload_picture_list : upload_picture_list
});
//循环把图片上传到服务器,并显示进度
for(var i in upload_picture_list){
if(upload_picture_list[i]['upload_percent'] == 0){
app.upload_file_server(that,upload_picture_list,i);
}
}
},
})
},



})


uploadimg.js

var urlStr = 'http://www.xxx.com';
var timestamp = Date.parse(new Date());
timestamp = timestamp / 1000;
function upload_file_server(that,upload_picture_list,j){
console.log("开始上传"+ j + "图片到服务器");
console.log(upload_picture_list[j]);
var upload_task = wx.uploadFile({
url: urlStr + '/testUpload.php',
filePath: upload_picture_list[j]['path'],//上传的文件本地地址,
name: 'file',
header: { "Content-Type": "multipart/form-data" },
fromData: { 'path': 'wxchat', 'session_token': wx.getStorageSync('session_token')},
success:function(res){
console.log(res);
var data = JSON.parse(res.data) //字符串转化为JSON
//console.log(data);return;
if (data.Success == true){
//console.log(data);
var filename = urlStr + data.savename;
upload_picture_list[j]['path_server'] = filename;
}
that.setData({
upload_picture_list: upload_picture_list
})
console.log("图片上传" + j + "到服务器完成:")
console.log(upload_picture_list[j])
}
})
upload_task.onProgressUpdate((res) => {
//console.log('上传进度', res.progress)
//console.log('已经上传的数据长度', res.totalBytesSent)
//console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
upload_picture_list[j]['upload_percent'] = res.progress;
console.log('第' + j + '个图片上传进度:' + upload_picture_list[j]['upload_percent'])
console.log(upload_picture_list)
that.setData({
upload_picture_list: upload_picture_list
})
})
}
module.exports.upload_file_server = upload_file_server; //这样暴露接口,这里不暴露是不能引用的



php
<?php $filename = 'file'; $imgname = $_FILES[$filename]['name']; $tmp = $_FILES[$filename]['tmp_name']; $filepath = '/uploads/test/'; $data['Success'] = false; $data['savename'] = ''; $allowtype = array('png', 'gif', 'jpg', 'jpeg'); //var_dump($imgname); $arr = explode(".",$imgname); $hz = $arr[count($arr)-1]; $randname = date("YmdHis").rand(100, 999).".".$hz; if(move_uploaded_file($tmp,'.'.$filepath.$randname)){ #echo $filepath.$imgname; $data['Success'] = true; $data['savename'] = $filepath.$randname; }else{ #echo "上传失败"; $data['Success'] = false; $data['savename'] = ''; } echo json_encode($data);

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权