微信小程序开发笔记
发布时间:2017-12-09, 10:17:28 分类:HTML | 编辑 off 网址 | 辅助
图集1/12
正文 4248字数 4,290,802阅读
微信小程序开发文档 微信开发者工具 WeUI微信小程序前端框架ui简明入门指南 微信小程序之购物车功能 微信小程序撸图片小试手
小程序让每个页面都有tabbar
写入日志
PHP调式bug
手机网页前端开发者调试面板 vConsole
PHP调式bug
手机网页前端开发者调试面板 vConsole
<?php
function xl_bug_log_text($content){
$file = 'xllog/'.date('Y-m-d').'.txt';//要写入文件的文件名(可以是任意文件名),如果文件不存在,将会创建一个
$content .= $content."\r\n";
if($f = file_put_contents($file, $content,FILE_APPEND)){
// 这个函数支持版本(PHP 5)
//echo "写入成功。<br />";
//return true;
}
return $f;
}
xl_bug_log_text('iswtf');
Run code
Cut to clipboard
微信小程序 MD5
md5.js
使用

md5.js
使用
var utilMd5 = require('../../utils/md5.js');
var password = utilMd5.hexMD5(password);
Run code
Cut to clipboard
构造令牌token
1.使用本地时间 注意时区差

2.使用服务器时间戳
小程序不支持wx.request同步请求
小程序为了用户体验,所有的request均为异步请求,不会阻塞程序运行
所以当你需要同步请求,锁死操作时,最好将所有的逻辑写在success:function(){}里面

util.js

ntime.php
服务器解密验证令牌
1.使用本地时间 注意时区差
//构造令牌
// 在需要使用的js文件中,导入js
//var util = require('../../utils/util.js');
var ttken ='JLI5vvqq0KRnzfla';//密钥
var ttime = parseInt(Date.parse(new Date())/1000);//时间 秒
//var ttime = util.ntime();
var ntoken=ttken+ttime;
var token = utilMd5.hexMD5(ntoken);
console.log(token);
//end
Run code
Cut to clipboard
2.使用服务器时间戳
小程序不支持wx.request同步请求
小程序为了用户体验,所有的request均为异步请求,不会阻塞程序运行
所以当你需要同步请求,锁死操作时,最好将所有的逻辑写在success:function(){}里面
//构造令牌 使用服务器时间戳
var util = require('../../utils/util.js');
util.ntime(utilMd5);
Run code
Cut to clipboard
util.js
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
//服务器时间戳
function ntime(utilMd5){
wx.request({
url: 'https://lizhenqiu.com/ntime.php',//请修改为你服务器
data: {
},
header: {
'content-type': 'application/json'
},
success: function (res) {
//return res;
var ttken = 'JLI5vvqq0KRnzfla';//密钥
//var ttime = parseInt(Date.parse(new Date()) / 1000);//时间 秒
var ttime = res;//util.ntime();
var ntoken = ttken + ttime;
var token = utilMd5.hexMD5(ntoken);
console.log(token);
//return token;
}
})
}
//构造令牌
// 在需要使用的js文件中,导入js
//var util = require('../../utils/util.js');
/*var ttken ='JLI5vvqq0KRnzfla';//密钥
var ttime = parseInt(Date.parse(new Date())/1000);//时间 秒
//var ttime = util.ntime();
var ntoken=ttken+ttime;
var token = utilMd5.hexMD5(ntoken);
console.log(token);*/
//end
module.exports = {
formatTime: formatTime,
ntime: ntime
}
Run code
Cut to clipboard
ntime.php
<?PHP
header("Content-type: text/html; charset=utf-8");
echo json_encode(time());
Run code
Cut to clipboard
服务器解密验证令牌
<?php
header("Content-type: text/html; charset=utf-8");
/*d s*/
error_reporting(E_ALL); //E_ALL
function cache_shutdown_error() {
$_error = error_get_last();
if ($_error && in_array($_error['type'], array(1, 4, 16, 64, 256, 4096, E_ALL))) {
echo '<font color=red>你的代码出错了:</font></br>';
echo '致命错误:' . $_error['message'] . '</br>';
echo '文件:' . $_error['file'] . '</br>';
echo '在第' . $_error['line'] . '行</br>';
}
}
register_shutdown_function("cache_shutdown_error");
function dump($vars){
echo '';
print_r($vars);
echo '
';
}
/*d e*/
//返回服务器时间戳
function ntime(){
return time();
}
//令牌验证 $t 时间 +- 范围 分
function xl_c_n_token($token,$t,$key){
$nt=ntime();
$t=($t+0)*60;//分化秒
$io=$nt-$t;
$it=$nt+$t;
for($i=$io;$i<$it;$i++){
$tokenlist[]=md5($key.$i);//所有时间误差返回内的token令牌
}
$iin=in_array($token,$tokenlist);
return $iin;
}
$ctoken=xl_c_n_token('80527e16009444c5d554d76134bf2471',5,'JLI5vvqq0KRnzfla');
//dump(xl_c_n_token('80527e16009444c5d554d76134bf2471',5,'JLI5vvqq0KRnzfla'));
function xl_bug_log_text($content){
$file = 'xllog/'.date('Y-m-d').'.txt';//要写入文件的文件名(可以是任意文件名),如果文件不存在,将会创建一个
$content .= $content."\r\n";
if($f = file_put_contents($file, $content,FILE_APPEND)){
// 这个函数支持版本(PHP 5)
//echo "写入成功。<br />";
return true;
}
return $f;
}
//xl_bug_log_text('iswtf');
//echo md5('password');
Run code
Cut to clipboard
(支付宝)给作者钱财以资鼓励 (微信)→
有过 20 条评论 »
1.先建立一个common.js文件,在common.js编写程序,
function myfunc() { console.log("myfunc...."); } module.exports.myfunc = myfunc; //暴露接口,这里不暴露不能引用
在文件域js内
var common = require("../../common.js");//去链接过来,光链接过来还不行 var app; var common = require("../../common.js"); Page({ data:{ }, onLoad:function() { app = getApp(); this.setData({version:app.globalData.appName}); common.myfunc(); //最后需要执行才能生效 } })
在小程序中,定义了一项工具文件utils,此文件的js旨在本文件之内有效,当其他子页面想调用其中的js方法或者变量时,需要两步骤:
1:在utils被调用的js文件中,面向对象的方式模型输出:
module.exports={要调用的函数名称:要调用的函数名称 }
2:在要调用的js文件中模块化引入utils的js文件
var object=require("utils被调用的js文件地址")
utils中被调用的js:
var URl='http://123.23.169'; var getImageurl=function(imageurl){ return URl+imageurl; } // 要引用这个文件的函数或者变量,除了在要引用的的js文件中模块化之外(var utils=require('js地址')), // 在被引用的的js中要通过 module.exports={a:a}作为面向对象的变量输出函数如下: module.exports={ URl:URl,//要引用的函数 xx:xx getImageurl:getImageurl }
要调用的js文件:
// 获得工具utils工具js里面函数,先模块化引用utils里面的js地址 reqiure('js地址')成一个面向对象 var utils=require('../../utils/app.js') // console.log(utils) 可查看获得的函数 console.log(utils.getImageurl('iamgeaaddress.png'))
that.setData(res.data)
var data=[{name:"a",age:12},{name:"b",age:11},{name:"c",age:13},{name:"d",age:14}]; for(var o in data){ alert(o); alert(data[o]); alert("text:"+data[o].name+" value:"+data[o].age ); }
或是
<script type="text/javascript"> function text(){ var json = {"options":"[{/"text/":/"王家湾/",/"value/":/"9/"},{/"text/":/"李家湾/",/"value/":/"10/"},{/"text/":/"邵家湾/",/"value/":/"13/"}]"} json = eval(json.options) for(var i=0; i<json.length; i++) { alert(json[i].text+" " + json[i].value) } } </script>
wx.chooseImage({ count: 1, // 默认9
这个count最大只能填写9(官方文档少了这个参数的具体描述)
var myDate = new Date();//获取系统当前时间 myDate.getYear(); //获取当前年份(2位) myDate.getFullYear(); //获取完整的年份(4位,1970-????) myDate.getMonth(); //获取当前月份(0-11,0代表1月) myDate.getDate(); //获取当前日(1-31) myDate.getDay(); //获取当前星期X(0-6,0代表星期天) myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数) myDate.getHours(); //获取当前小时数(0-23) myDate.getMinutes(); //获取当前分钟数(0-59) myDate.getSeconds(); //获取当前秒数(0-59) myDate.getMilliseconds(); //获取当前毫秒数(0-999) myDate.toLocaleDateString(); //获取当前日期 var mytime=myDate.toLocaleTimeString(); //获取当前时间 myDate.toLocaleString( ); //获取日期与时间
第一种方法:
var timestamp =Date.parse(new Date());
第二种方法:
var timestamp =(new Date()).valueOf();
结果:1280977330748
第三种方法:
var timestamp=new Date().getTime();
结果:1280977330748
显示的结果是:Mar 31 10:10:43 UTC+0800 2012 这种格式的时间
但是用new Date() 参与计算会自动转换为从1970.1.1开始的毫秒数。
<script> alert(Date.parse('Jul 8, 2005')); alert(new Date()); alert(parseInt(new Date())); </script>
new Date() ; //参数可以为整数; 也可以为字符串; 但格式必须正确 new Date(2009,1,1); //正确 new Date("2009/1/1"); //正确 new Date("2009-1-1"); //错误
1.丢弃小数部分,保留整数部分 parseInt(5/2) 2.向上取整,有小数就整数部分加1 Math.ceil(5/2) 3,四舍五入. Math.round(5/2) 4,向下取整 Math.floor(5/2) Math 对象的方法 FF: Firefox, N: Netscape, IE: Internet Explorer 方法 描述 FF N IE abs(x) 返回数的绝对值 1 2 3 acos(x) 返回数的反余弦值 1 2 3 asin(x) 返回数的反正弦值 1 2 3 atan(x) 以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值 1 2 3 atan2(y,x) 返回从 x 轴到点 (x,y) 的角度(介于 -PI/2 与 PI/2 弧度之间) 1 2 3 ceil(x) 对一个数进行上舍入。 1 2 3 cos(x) 返回数的余弦 1 2 3 exp(x) 返回 e 的指数。 1 2 3 floor(x) 对一个数进行下舍入。 1 2 3 log(x) 返回数的自然对数(底为e) 1 2 3 max(x,y) 返回 x 和 y 中的最高值 1 2 3 min(x,y) 返回 x 和 y 中的最低值 1 2 3 pow(x,y) 返回 x 的 y 次幂 1 2 3 random() 返回 0 ~ 1 之间的随机数 1 2 3 round(x) 把一个数四舍五入为最接近的整数 1 2 3 sin(x) 返回数的正弦 1 2 3 sqrt(x) 返回数的平方根 1 2 3 tan(x) 返回一个角的正切 1 2 3 toSource() 代表对象的源代码 1 4 - valueOf() 返回一个 Math 对象的原始值 代码案例: <script type="text/javascript"> //取整 function getResult(num){ return parseInt(num); } //四舍五入到num后面的n位 function getResult(num,n){ return Math.round(num*Math.pow(10,n))/Math.pow(10,n); } //截取n位 function getresult(num,n){ return num.toString().replace(new RegExp("^(\\-?\\d*\\.?\\d{0,"+n+"})(\\d*)$"),"$1")+0; } 其他: var mLength = textMn.length; var mFirst = parseInt(mLength/60); //取整 //alert(mLength); var mLast = mLength; //取余 if(mLast>0){ $(".mood_content").height((mFirst+1)*20); }
const formatTime = date => { const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':') } const formatNumber = n => { n = n.toString() return n[1] ? n : '0' + n } //服务器时间戳 function ntime(utilMd5, that){ wx.request({ url: 'https://hhh.liangtianmei.com/ntime.php',//请修改为你服务器 data: { }, header: { 'content-type': 'application/json' }, success: function (res) { //return res; var ttken = 'JLI5vvqq0KRnzfla';//密钥 //var ttime = parseInt(Date.parse(new Date()) / 1000);//时间 秒 var ttime = res.data;//util.ntime(); var ntoken = ttken + ttime; var token = utilMd5.hexMD5(ntoken); //console.log(token); //return token; var url = 'https://hhh.liangtianmei.com/index.php/Home/Product/index'; updatenew(url, token, that); } }) } //更新数据 function updatenew(url, token, that) { wx.request({ url: url,//'https://hhh.liangtianmei.com/index.php/Home/Product/index', //仅为示例,并非真实的接口地址 data: { token: token }, method: 'GET', header: { 'content-type': 'application/json' // 默认值 }, success: function (res) { // alert(res.data) // res.data.content = app.convertHtmlToText(res.content) /*that.setData({ textdata: res.data }); console.log (res.data)*/ // that.setData(res.data) /*that.setData({ all: res.data//第一个data为固定用法,第二个data是json中的data })*/ //console.log(token); //console.log(res) that.setData({ all: res.data // imageUrl: "../images/sp_07.png"//触发事件时的图片 }) } }) } //构造令牌 // 在需要使用的js文件中,导入js //var util = require('../../utils/util.js'); /*var ttken ='JLI5vvqq0KRnzfla';//密钥 var ttime = parseInt(Date.parse(new Date())/1000);//时间 秒 //var ttime = util.ntime(); var ntoken=ttken+ttime; var token = utilMd5.hexMD5(ntoken); console.log(token);*/ //end module.exports = { formatTime: formatTime, ntime: ntime }
//构造令牌 使用服务器时间戳 var utilMd5 = require('../../utils/md5.js'); var util = require('../../utils/util.js'); // pages/product/product.js Page({ /** * 页面的初始数据 */ data: { // tabs:["泰国香米","湖北早梗米"], // clickId:0,//默认选中的键值,从零开始 // imageUrl:'../images/sp_0777.png'//默认图片 titlessss:'产品中心' }, btn_primary: function (event) { console.log(event) var that = this; this.setData({ clickId: event.currentTarget.id, // imageUrl: "../images/sp_07.png"//触发事件时的图片 }) } , /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; var app = getApp();//获取app小程序实例 // WxParse.wxParse('content', 'html', content, that, 5) wx.login({ success: function (res) { if (res.code) { //更新数据 util.ntime(utilMd5, that); } } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
WXML
<!--index.wxml--> <swiper indicator-dots="{{indicatorDots}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" indicator-dots="true" style="height:{{imgheightsheight}}px;"> <block wx:for="{{imgUrls}}"> <swiper-item> <image src="{{item}}" class="slide-image" width="100%" bindload="imageLoad" style="width:100%;height:{{imgheightsheight}}px;" /> </swiper-item> </block> </swiper>
JS
Page({ data: { imgUrls: [ 'http://newtest.test2.resonance.net.cn/xcximg/01.jpg', 'http://newtest.test2.resonance.net.cn/xcximg/01.jpg', 'http://newtest.test2.resonance.net.cn/xcximg/01.jpg' ], indicatorDots: false, autoplay: false, interval: 5000, duration: 1000 }, changeIndicatorDots: function (e) { this.setData({ indicatorDots: !this.data.indicatorDots }) }, changeAutoplay: function (e) { this.setData({ autoplay: !this.data.autoplay }) }, intervalChange: function (e) { this.setData({ interval: e.detail.value }) }, durationChange: function (e) { this.setData({ duration: e.detail.value }) }, imageLoad: function (e) { //获取图片真实宽度 //var imgwidth = e.detail.width, //imgheight = e.detail.height, //宽高比 //ratio = imgwidth / imgheight; //console.log(imgwidth, imgheight) var imageSize = {}; var originalWidth = e.detail.width;//图片原始宽 var originalHeight = e.detail.height;//图片原始高 var originalScale = originalHeight / originalWidth;//图片高宽比 var that=this //获取屏幕宽高 wx.getSystemInfo({ success: function (res) { var windowWidth = res.windowWidth; var windowHeight = res.windowHeight; var windowscale = windowHeight / windowWidth;//屏幕高宽比 //console.log('windowWidth: ' + windowWidth) //console.log('windowHeight: ' + windowHeight) if (originalScale < windowscale) {//图片高宽比小于屏幕高宽比 //图片缩放后的宽为屏幕宽 imageSize.imageWidth = windowWidth; imageSize.imageHeight = (windowWidth * originalHeight) / originalWidth; } else {//图片高宽比大于屏幕高宽比 //图片缩放后的高为屏幕高 imageSize.imageHeight = windowHeight; imageSize.imageWidth = (windowHeight * originalWidth) / originalHeight; } that.setData({ imgheightsheight: windowHeight, }) } }) //console.log(imageSize); //计算的高度值 //var viewHeight = 750 / ratio; // var imgheight = viewHeight ///var imgheights = this.data.imgheights //把每一张图片的高度记录到数组里 /*imgheights.push(imgheight) this.setData({ imgheights: imgheights, })*/ }, })
data: { //图片 hdimg: [], //是否采用衔接滑动 circular: true, //是否显示画板指示点 indicatorDots: false, //选中点的颜色 indicatorcolor: "#000", //是否竖直 vertical: false, //是否自动切换 autoplay: false, //滑动动画时长毫秒 duration: 100, //所有图片的高度 imgheights: [], //图片宽度 imgwidth: 750, //默认 current:0 },
imageLoad: function (e) { //获取图片真实宽度 var imgwidth = e.detail.width, imgheight = e.detail.height, //宽高比 ratio = imgwidth / imgheight; console.log(imgwidth, imgheight) //计算的高度值 var viewHeight = 750 / ratio; var imgheight = viewHeight var imgheights = this.data.imgheights //把每一张图片的高度记录到数组里 imgheights.push(imgheight) this.setData({ imgheights: imgheights, }) }, bindchange: function (e) { console.log(e.detail.current) this.setData({ current: e.detail.current}) }
<view> <swiper class="swiper" indicator-dots="{{indicatorDots}}" vertical="{{vertical}}" autoplay="{{autoplay}}" duration="{{duration}}" bindchange="bindchange" circular="{{circular}}" style="height:{{imgheights[current]}}rpx;"> <block wx:for="{{hdimg}}" wx:key="{{index}}"> <swiper-item > <image src="{{item}}" mode="aspectFit" bindload="imageLoad" class=".itemimage" style="height:{{imgheights[current]}}rpx;width:{{imgwidth}}rpx;"/> </swiper-item> </block> </swiper> </view>
.swiper { width: 100%; }
修复版本高度100%bug上算法计算高度有问题
Page({ data: { imgUrls: [ 'http://newtest.test2.resonance.net.cn/xcximg/02.jpg?1', 'http://newtest.test2.resonance.net.cn/xcximg/03.jpg?1', 'http://newtest.test2.resonance.net.cn/xcximg/04.jpg?1' ], indicatorDots: false, autoplay: false, interval: 5000, duration: 1000 }, changeIndicatorDots: function (e) { this.setData({ indicatorDots: !this.data.indicatorDots }) }, changeAutoplay: function (e) { this.setData({ autoplay: !this.data.autoplay }) }, intervalChange: function (e) { this.setData({ interval: e.detail.value }) }, durationChange: function (e) { this.setData({ duration: e.detail.value }) }, imageLoad: function (e) { //获取图片真实宽度 //var imgwidth = e.detail.width, //imgheight = e.detail.height, //宽高比 //ratio = imgwidth / imgheight; //console.log(imgwidth, imgheight) var imageSize = {}; var originalWidth = e.detail.width;//图片原始宽 var originalHeight = e.detail.height;//图片原始高 var originalScale = originalHeight / originalWidth;//图片高宽比 var that=this //获取屏幕宽高 wx.getSystemInfo({ success: function (res) { var windowWidth = res.windowWidth; var windowHeight = res.windowHeight; //var windowscale = windowHeight / windowWidth;//屏幕高宽比 //console.log('windowWidth: ' + windowWidth) //console.log('windowHeight: ' + windowHeight) /*if (originalScale < windowscale) {//图片高宽比小于屏幕高宽比 //图片缩放后的宽为屏幕宽 imageSize.imageWidth = windowWidth; imageSize.imageHeight = (windowWidth * originalHeight) / originalWidth; } else {//图片高宽比大于屏幕高宽比 //图片缩放后的高为屏幕高 imageSize.imageHeight = windowHeight; imageSize.imageWidth = (windowHeight * originalWidth) / originalHeight; }*/ var imgheightsheight = originalScale * windowWidth;//(windowHeight * originalWidth) / windowWidth //console.log(imgheightsheight); that.setData({ imgheightsheight: imgheightsheight, }) } }) //console.log(imageSize); //计算的高度值 //var viewHeight = 750 / ratio; // var imgheight = viewHeight ///var imgheights = this.data.imgheights //把每一张图片的高度记录到数组里 /*imgheights.push(imgheight) this.setData({ imgheights: imgheights, })*/ }, })
<!--pages/product/product.wxml--> <view class="container"> <view bindtap="bindViewTap" class="userinfo"> <image class="userinfo-avatar" src="../images/ab_banner.jpg" background-size="cover" background-position="center"></image> <!-- <text class="userinfo-nickname">{{userInfo.nickName}}</text>--> </view> <view class="usermotto"> <text class="user-motto" >{{titlessss}}</text> </view> <text class="pice{{jzzz}}">加载中 </text> <block wx:for="{{all}}"> <view class="companyprofile"> <!-- pice{{jzzzs}}--> <view class="left"> <image class="companyimg" src="https://hhh.liangtianmei.com{{item.imgurl}}" background-size="cover"></image> </view> <view class="right"> <navigator url="../prodetail/prodetail?title={{item.title}}"> <text class="companytitle">{{item.title}}\n</text> </navigator> <text class="companymain">{{item.content}}</text> <text class="pice">¥100 </text> <block wx:if="{{index==clickId}}"> <image id="{{index}}" class="shopimg" src="../images/red.png" bindtap="btn_primary"></image> </block> <block wx:else> <image id="{{index}}" class="shopimg" src="../images/sp_0777.png" bindtap="btn_primary"></image> </block> <view class="stepper" > <text class="{{minusStatus}}" bindtap="bindMinusssss" id="{{index}}">-</text> <!-- 减号 <block wx:if="{{index==clickId}}"> <text class="{{minusStatus}}" bindtap="bindMinus" id="{{index}}">-</text> </block> <block wx:else> <text class="{{minusStatus}}" bindtap="bindMinus" id="{{index}}">-</text> </block>--> <!-- 数值 --> <block wx:if="{{index==clickId}}"> <input type="number" bindchange="bindManual" value="{{num}}" id="{{index}}"/> </block> <block wx:else> <input type="number" value="{{item.nnum}}" name="nnum" id="nnum{{index}}"/> <!--bindchange="bindManual" --> </block> <text class="normal" bindtap="bindPlussssss" id="{{index}}">+</text> <!-- 加号 <block wx:if="{{index==clickId}}"> <text class="normal" bindtap="bindPlus" id="{{index}}">+</text> </block> <block wx:else> <text class="normal" bindtap="bindPlus" id="{{index}}">+</text> </block>--> </view> <!-- <view class="icon"> <image id="{{index}}" class="add" src="../images/add.png" bindtap="btn_primary"></image> <text class="companymain">1</text> <image id="{{index}}" class="minus" src="../images/minus.jpg" bindtap="btn_primary"></image> </view>--> <!-- <view class="icon"> <image src="../images/add.png" class="add-img {{item.numbers==0 ?'none':''}}" bindtap="reduceNum" data-index="{{index}}"></image> <view class="num {{item.numbers==0?'none':''}}">{{item.id}}</view> <image src="../images/minus.jpg" class="add-img" bindtap="addNum" data-index="{{index}}" data-index="{{index}}"></image> </view> --> </view> </view> </block> <!-- <view class="companyprofile"> <view class="left"> <image class="companyimg" src="../images/ab_01.jpg" background-size="cover"></image> </view> <view class="right"> <text class="companytitle">湖北早梗米\n</text> <text class="companymain">浙江百慕生物科技有限公司隶属浙江丽珀集团,成立于2011年3月,注册资本1000万元,是一家从事海洋生物开发销售的公司,主要从事保健品(海参)产品的销售。</text> <text class="pice">¥120 </text> <image class="shopimg" src="{{imageUrl}}" bindtap="btn_primary" ></image> </view> </view> --> <view class="footer"> <text class="footerword">版权所有©2016 全家科技发展有限公司</text> </view> </view>
小程序购物者加减数量输入框获取value
微信小程序获取value 微信小程序如何获取单个input值
微信小程序—如何获取用户输入文本框的值
微信小程序获取用户输入 微信小程序怎么获取用户输入
//构造令牌 使用服务器时间戳 var utilMd5 = require('../../utils/md5.js'); var util = require('../../utils/util.js'); // pages/product/product.js Page({ /** * 页面的初始数据 */ data: { // tabs:["泰国香米","湖北早梗米"], // clickId:0,//默认选中的键值,从零开始 // imageUrl:'../images/sp_0777.png'//默认图片 titlessss:'产品中心', jzzzs:1, num: 0, // 使用data数据对象设置样式名 minusStatus: 'disabled' , inputTxt:0 }, /* 点击减号 */ bindMinus: function (event) { var num = this.data.num; // 如果大于1时,才可以减 if (num > 1) { num--; } // 只有大于一件的时候,才能normal状态,否则disable状态 var minusStatus = num <= 1 ? 'disabled' : 'normal'; // 将数值与状态写回 this.setData({ num: num, minusStatus: minusStatus, clickId: event.currentTarget.id }); }, bindMinusssss:function(e){ //new 2017.12.19 var id = e.currentTarget.id; var all = this.data.all; if (!all[id].nnum) all[id].nnum = 1; var nv = all[id].nnum; if(nv>1) nv-=1; all[id].nnum=nv; this.setData({ all: all }) //e.detail = { nv, cursor } //e.detail.value=100; //console.log(all); //console.log(e.currentTarget.dataset.value); }, bindPlussssss: function (e) { //new 2017.12.19 var id = e.currentTarget.id; var all = this.data.all; if (!all[id].nnum) all[id].nnum = 1; var nv = all[id].nnum; nv += 1;//记得判断是否超过库存 all[id].nnum = nv; this.setData({ all: all }) //e.detail = { nv, cursor } //e.detail.value=100; //console.log(all); //console.log(e.currentTarget.dataset.value); }, /* 点击加号 */ bindPlus: function (event) { var num = this.data.num; // 不作过多考虑自增1 num++; // 只有大于一件的时候,才能normal状态,否则disable状态 var minusStatus = num < 1 ? 'disabled' : 'normal'; // 将数值与状态写回 this.setData({ num: num, minusStatus: minusStatus, clickId: event.currentTarget.id }); }, /* 输入框事件 */ bindManual: function (event) { //var clickId = event.detail.id; // console.log(clickId) var num = event.detail.value; console.log(num) var that = this; // 将数值与状态写回 this.setData({ num: num, clickId: event.currentTarget.id }); } , btn_primary: function (event) { console.log(event) var that = this; this.setData({ clickId: event.currentTarget.id, // imageUrl: "../images/sp_07.png"//触发事件时的图片 }) } , /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; var app = getApp();//获取app小程序实例 // WxParse.wxParse('content', 'html', content, that, 5) wx.login({ success: function (res) { if (res.code) { //更新数据 var url = 'https://hhh.liangtianmei.com/index.php/Home/Product/index'; util.ntime(utilMd5, that,url); } } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
var app = getApp() //构造令牌 // 在需要使用的js文件中,导入js //var util = require('../../utils/util.js'); //构造令牌 使用服务器时间戳 var utilMd5 = require('../../utils/md5.js'); var util = require('../../utils/util.js'); var ttken = 'JLI5vvqq0KRnzfla';//密钥 var ttime = parseInt(Date.parse(new Date()) / 1000);//时间 秒 //var ttime = util.ntime(); var ntoken = ttken + ttime; var token = utilMd5.hexMD5(ntoken); //console.log(token); //end Page({ /** * 页面的初始数据 */ data: { token:0, tokenid: 0 }, onLoad: function () { //console.log('token: ' + token); var params = { 'name': 'json', 'age': 26 }; //util.makeusertoken() //初始化 验证码 util.updatenew('https://hhh.*****.com/index.php/Home/Wxapp/code/token/' + token, token,this); //获取验证码图片 var tokenid = wx.getStorageSync('tokenid'); //util.updatenew('https://hhh.*****.com/index.php/Home/Wxapp/getcode/token/' + token + '/tokenid/' + tokenid+'/'); this.setData({ token: token, tokenid:tokenid }) }, changing:function(){ util.updatenew('https://hhh.*****.com/index.php/Home/Wxapp/code/token/' + token, token, this); var tokenid = wx.getStorageSync('tokenid'); this.setData({ token: token, tokenid: tokenid }) } }) //ajax(method, url, data, success)
1.生成令牌 <image style="height:40px;width:100px;margin-top:10px;" bindtap="changing" id="codeyzmm" src="https://hhh.*****.com/index.php/Home/Wxapp/getcode/token/{{token}}/tokenid/{{tokenid}}/" ></image>
const formatTime = date => { const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':') } const formatNumber = n => { n = n.toString() return n[1] ? n : '0' + n } //服务器时间戳 function ntime(utilMd5, that,url){ wx.request({ url: 'https://hhh.*****.com/ntime.php',//请修改为你服务器 data: { }, header: { 'content-type': 'application/json' }, success: function (res) { //return res; var ttken = 'JLI5vvqq0KRnzfla';//密钥 //var ttime = parseInt(Date.parse(new Date()) / 1000);//时间 秒 var ttime =res.data;//util.ntime(); var ntoken = ttken + ttime; var token = utilMd5.hexMD5(ntoken); //console.log(ntoken); //return token; // var url = 'https://hhh.*****.com/index.php/Home/Product/index'; updatenew(url, token, that); } }) } //更新数据 function updatenew(url, token, that) { wx.request({ url: url,//'https://hhh.*****.com/index.php/Home/Product/index', //仅为示例,并非真实的接口地址 /*data: { token: token },*/ method: 'GET', header: { 'content-type': 'application/json' // 默认值 }, success: function (res) { // alert(res.data) // res.data.content = app.convertHtmlToText(res.content) /*that.setData({ textdata: res.data }); console.log (res.data)*/ // that.setData(res.data) /*that.setData({ all: res.data//第一个data为固定用法,第二个data是json中的data })*/ //console.log(token); //res.data.jzzz = 1; if (res.data.tokenid){ //保存token id wx.setStorageSync('tokenid', res.data.tokenid); } if (that){ that.setData(res.data) //that.setData({ //jzzz:1, //jzzzs:'', //codeimgurl: res.data.codeimgurl, //all: res.data //res // imageUrl: "../images/sp_07.png"//触发事件时的图片 //}) } } }) } //构造令牌 // 在需要使用的js文件中,导入js //var util = require('../../utils/util.js'); /*var ttken ='JLI5vvqq0KRnzfla';//密钥 var ttime = parseInt(Date.parse(new Date())/1000);//时间 秒 //var ttime = util.ntime(); var ntoken=ttken+ttime; var token = utilMd5.hexMD5(ntoken); console.log(token);*/ //end //随机字符窜 function randomString(len) { len = len || 32; var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhioOLl,9gq,Vv,Uu,I1jkmnprstwxyz/*~!@#¥%……&*()+=-2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/ var maxPos = $chars.length; var pwd = ''; for (var i = 0; i < len; i++) { pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); } return pwd; } //document.write(randomString(32)); /*伪身份凭证*/ function makeusertoken(){ //console.log(randomString(9)) var ro = randomString(9); //存储随机字符1 wx.setStorageSync('ros', ro); //var code = ro.charCodeAt(); //var nro = wx.getStorageSync('ros') //console.log(strToBinary(ro)); //console.log(binaryToStr('1000010 1000010 111000 1101011 1001101 1000000 110001 1101100 1111001')); } //将字符串转换成二进制形式,中间用空格隔开 function strToBinary(str) { var result = []; var list = str.split(""); for (var i = 0; i < list.length; i++) { if (i != 0) { result.push(" "); } var item = list[i]; var binaryStr = item.charCodeAt().toString(2); result.push(binaryStr); } return result.join(""); } //将二进制字符串转换成Unicode字符串 function binaryToStr(str) { var result = []; var list = str.split(" "); for (var i = 0; i < list.length; i++) { var item = list[i]; var asciiCode = parseInt(item, 2); var charValue = String.fromCharCode(asciiCode); result.push(charValue); } return result.join(""); } /*end*/ //获取访问者的openid /*end*/ module.exports = { formatTime: formatTime, ntime: ntime, updatenew: updatenew, makeusertoken: makeusertoken }
wx.navigateTo({ url: 'test?id=1'//实际路径要写全 })
//test.js Page({ onLoad: function(option){ console.log(option.id) } })
参数与路径之间使用?分隔,参数键与参数值用=相连,不同参数用&分隔;
test?id=1 中id为参数键,1 为参数值
在目的页面中onLoad()方法中option对象即为参数对象,可以通过参数键来取出参数值
var App = getApp(); // pages/about/about.js Page({ /** * 页面的初始数据 */ data: { "content": '广西南宁共振广告有限公司,2008年成立于南宁,是一家以“品牌咨询+品牌设计+品牌策划+品牌落地”于一体的品牌服务平台,通过360°全景式纵深品牌打造,从品牌标识设计、VI设计、空间设计、包装、海报等多维度构建完善的品牌价值链,致力于以实战服务中国企业,以品牌推动中国成长。公司创立至今,已是当之无愧的品牌实战专家,客户涵盖国内外地产、金融、IT、汽车、服装时尚、奢侈品、能源、机械、快速消费品等各行业著名的企业,深受客户信赖。我们坚持以实力深耕市场,力求达成艺术与商业之间、客户与市场之间、虚拟与现实之间的价值共生,将企业打造成为一个能为客户提供综合化', "content2": '更换内容21321', "content3": '2222222222222更换内容21321', radioCheckVal: 0, all: [{ one: "公司介绍", two: '../../images/ab2.gif', two1: '../../images/ab5.gif' }, { one: "公司理念", two: '../../images/ab3.gif', two1: '../../images/ab4.gif' }, { one: "核心优势", two: '../../images/ab4.gif', two1: '../../images/ab3.gif' }, { one: "公司使命", two: '../../images/ab5.gif', two1: '../../images/ab2.gif' }], oall:{ } }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { App.editTabBar(this); this.setData({ "oall": this.data.all })//保存初始图片数据 2018.01.05 }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, //更换内容 getnewcontent:function(n){ var cc = (n.currentTarget.dataset.c); var ncc ='content'+cc; // var adata =''; var id = n.currentTarget.dataset.id; //打印可以看到,此处已获取到了包含id、title、和content的对象 var that = this; //var two = all[id].two = all[id].two1; this.setData({ "all":this.data.oall },function(){ that.data.all[id].two = that.data.all[id].two1; //console.log(that.data.all); var all = that.data.all; that.setData({ "content": that.data[ncc], "all": all, "id": id }) }); } })
<!-------------banner 开始--------------> <image style='width:100%;' src='../../images/ab0.png' mode="widthFix" ></image> <!-------------banner 结束--------------> <view class="about" style="background:url('https://hhh.liangtianmei.com/images/bjjj.png');"> <!-------------标题 开始--------------> <view class='title'> <view class='zuo'> <view class='xian'></view> <view class='yuan'>●</view> </view> <view class='wz'> <text class='yw'>ABOUT SU\n</text> <text class='zw'>关于我们\n</text> </view> <view class='you'> <view class='yuan'>●</view> <view class='xian'></view> </view> </view> <!-------------标题 结束--------------> <!-------------导航 开始--------------> <view class='nav'> <view class='meiyi'> <block wx:for="{{all}}"> <view class="dg" bindtap="getnewcontent" data-id="{{index}}" data-c='{{index+1}}' style="{{index == id?' border:1rpx solid red':'border:1rpx solid gainsboro;'}}"> <image src="{{item.two}}" mode="widthFix" data-index="{{index}}"></image> <text>{{item.one}}</text> </view> </block> <!-- <view class='dg' bindtap="getnewcontent" data-c='2'> <image src='../../images/ab2.gif' mode="widthFix"></image>\r\n <text>公司介绍</text> </view> <view class='dg' bindtap="getnewcontent" data-c='3'> <image src='../../images/ab3.gif' mode="widthFix"></image>\r\n <text>公司理念</text> </view> <view class='dg'> <image src='../../images/ab4.gif' mode="widthFix"></image>\r\n <text>核心优势</text> </view> <view class='dg'> <image src='../../images/ab5.gif' mode="widthFix"></image>\r\n <text>公司使命</text> </view>--> </view> </view> <!-------------导航 结束--------------> <!-------------图文 开始--------------> <view class='nr'> <image src='../../images/ab1.png' mode="widthFix"></image> <text>{{content}}</text> </view> <!-------------图文 结束--------------> </view> <import src="../template/tabBar.wxml" /> <template is="tabBar" data="{{tabBar: tabBar}}" />
微信模板文件wxml循坏遍历怎么json键名变量??
getnewcontent:function(n){ var cc = (n.currentTarget.dataset.c); var ncc ='content'+cc; var id = n.currentTarget.dataset.id; this.setData({ "content": this.data[ncc], id:id }) } <block wx:for="{{all}}"> <view class='dg' data-id="{{index}}" bindtap="getnewcontent" data-c='{{index+1}}'> <block wx:if="{{index==id}}"> <image src='{{item.two1}}' mode="widthFix"></image>\r\n </飙泪ock> <block wx:else> <image src='{{item.two}}' mode="widthFix"></image>\r\n </飙泪ock> <text>{{item.one}}</text> <iew> </飙泪ock>
this.setData({userInfo: userInfo}, callback)
*/ onLoad: function (options) { var that = this; App.editTabBar(that); // var ajaxdata //console.log(that.data); var url = 'https://ssl.resonance.net.cn/test/index.php/Home/About/index'; util.ntime(utilMd5, that, url, "calll"); }, calll: function (that,res){ //console.log(res.content) WxParse.wxParse('article', 'html', res.content, that, 5); }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { function updatenew(url, token, that, calll) { that.setData(res.data, that.calll(that,res.data))
setTimeout(回调函数,时间,参数1,...,参数n)
常用属性:
swiper.wxml添加代码:
<swiper indicator-dots="{{indicatorDots}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}} " bindchange="bindchangeTag"> <block wx:for="{{imgUrls}}"> <swiper-item> <image src="{{item}}" class="slide-image"/> </swiper-item> </block> </swiper> <button bindtap="changeIndicatorDots"> 是否显示面板指示点 </button> <button bindtap="changeAutoplay"> 是否自动切换 </button> <slider bindchange="intervalChange" show-value min="1000" max="2000"/> 自动切换时间间隔 <slider bindchange="durationChange" show-value min="1800" max="10000"/> 滑动动画时长
js:
Page({ data: { imgUrls: [ 'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg', 'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg', 'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg' ], indicatorDots: false, autoplay: false, interval: 1000, duration: 1800 }, //是否显示面板指示点 changeIndicatorDots: function(e) { this.setData({ indicatorDots: !this.data.indicatorDots }) }, //是否自动切换 changeAutoplay: function(e) { this.setData({ autoplay: !this.data.autoplay }) }, //自动切换时间间隔 intervalChange: function(e) { this.setData({ // e.detail.value获取slider的值 interval: e.detail.value }) }, //滑动动画时长 durationChange: function(e) { this.setData({ duration: e.detail.value }) }, //当页面改变是会触发 bindchangeTag:function(e){ console.log("bindchangeTag...") }, onLoad:function(options){ // 页面初始化 options为页面跳转所带来的参数 }, onReady:function(){ // 页面渲染完成 }, onShow:function(){ // 页面显示 }, onHide:function(){ // 页面隐藏 }, onUnload:function(){ // 页面关闭 } })
css:
.slide-image{ width: 100%; height: 160px; }
swiper 滑块视图容器
this.setData({ ['array[' + index + '].text']:'changed data' })
var param = {}; var string = "array["+index+"].text; param[string] = 'changed data'; that.setData(param);
display:inline-block
某些手机机型不显示,加最上面层级 z-index:9999
解决办法:用setTimeout将wx.reLaunch包裹起来,200ms就差不多
setTimeout(function() { wx.reLaunch({ url: '../goodsDetail/goodsDetail', }) }, 200)
似乎wx.reLaunch触发是在页面onshow之后,所以给了一个200ms的延迟
mpvue,可以在 onLoad 时用 Object.assign(this, this.$options.data()) 来清理微信缓存
txt.replace(/\s+/g, '');//输入框自动去除空格
wx.showModal({ title: '提示', content: '第一行内容\r\n第二行内容\r\n第三行内容\r\n第四行内容', success: function(res) { if (res.confirm) { console.log('用户点击确定') } else if (res.cancel) { console.log('用户点击取消') } } })
php返回json数组前面出现乱码“锘縶”解决办法
去除了半天bom没好使,真是坑爹,最后在返回接口前面加ob_clean()完美解决:
thinkphp json头部乱码 
<?php if (isset($_GET['dir'])){ $basedir=$_GET['dir']; }else{ $basedir = '.'; } $auto = 1; checkdir($basedir); function checkdir($basedir){ if ($dh = opendir($basedir)) { while (($file = readdir($dh)) !== false) { if ($file != '.' && $file != '..'){ if (!is_dir($basedir."/".$file)) { echo "filename: $basedir/$file ".checkBOM("$basedir/$file")." \n\r"; }else{ $dirname = $basedir."/".$file; checkdir($dirname); } } } closedir($dh); } } function checkBOM ($filename) { global $auto; $contents = file_get_contents($filename); $charset[1] = substr($contents, 0, 1); $charset[2] = substr($contents, 1, 1); $charset[3] = substr($contents, 2, 1); if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) { if ($auto == 1) { $rest = substr($contents, 3); rewrite ($filename, $rest); return ("<font color=red>BOM found, automatically removed.</font>"); }else { return ("<font color=red>BOM found.</font>"); } }else return ("BOM Not Found."); } function rewrite ($filename, $data) { $filenum = fopen($filename, "w"); flock($filenum, LOCK_EX); fwrite($filenum, $data); fclose($filenum); }
<view class='zright' bindtap='choseCoupon' data-info='{{item}}' data-id='{{index}}'> choseCoupon: function (e) { console.log(e.currentTarget.dataset.id) console.log(e.currentTarget.dataset.info) }
wx.reLaunch({ url: 'test?id=1' })
mode="widthFix" style="width:122px;"
DB::table(test)->increment('num',1,['vote'=>DB::raw('`vote`+1')]);
$bigImgPath = "./images/bg.jpg"; $qCodePath = "./images/thumb/$id.jpg"; $bigImg = imagecreatefromstring(file_get_contents($bigImgPath)); $qCodeImg = imagecreatefromstring(file_get_contents($qCodePath)); list($qCodeWidth, $qCodeHight, $qCodeType) = getimagesize($qCodePath); imagecopymerge($bigImg, $qCodeImg, 239, 677, 0, 0, $qCodeWidth, $qCodeHight, 100); list($bigWidth, $bigHight, $bigType) = getimagesize($bigImgPath); imagejpeg($bigImg,'./images/'.$id.'.jpg');
<!-- 如果有日期输出,即$data.time不为空且不为0,则格式化时间戳,否则默认当前时间戳,并格式化成日期格式 --> {$data.time|default=time()|date='Y-m-d',###} <!--转换为时间戳格式--> {'2014-09-02'|strtotime} <!--将时间转换为时间戳在转换为自己想要的格式--> {'2014-09-02 12:59:12'|strtotime|date='Y-m-d',###}
<?php echo $showtime=date("Y-m-d H:i:s");?>
$file->getInfo();
错误789:L2TP连接尝试失败,因为安全层在初始化与远程计算机的协商时遇到一个处理
thinkphp alias jion
微信小程序刷新
微信小程序**this
小程序Bad attr `wx:key` with message: unexpected token `*`.
微信公众号获取设备信息
微信公众号获取手机型号
\DB::table
thinkphp foreach 空
百度地图经纬度校正
js中load与onload的区别
DolphinPHP
myql join 相同字段
thinkphp field as
$conn->connect_error
Laravel 清理缓存 "php artisan config:clear"
设置navicat for mysql导入文件大小限制
把max_allowed_packet设置为100M
thinkphp join联表查询 多表联查:
$user = M('user'); $b_user = M('b_user'); $c_user = M('c_user'); $list = $user->alias('user')->where('user.user_type=1') ->join('b_user as b on b.b_userid = user.user_id') ->join('c_user as c on c.c_userid = b.b_userid') ->order('b.user_time') ->select();
$user 表的 user_id 等于$b_user表的b_userid;
$c_user表的 c_userid 等于$b_user表的b_userid;
/** * 基于PHP的 mb_substr,iconv_substr 这两个扩展来截取字符串,中文字符都是按1个字符长度计算; * 该函数仅适用于utf-8编码的中文字符串。 * * @param $str 原始字符串 * @param $length 截取的字符数 * @param $append 替换截掉部分的结尾字符串 * @return 返回截取后的字符串 */ function sub_str($str, $length = 0, $append = '...') { $str = trim($str); $strlength = strlen($str); if ($length == 0 || $length >= $strlength) { return $str; } elseif ($length < 0) { $length = $strlength + $length; if ($length < 0) { $length = $strlength; } } if ( function_exists('mb_substr') ) { $newstr = mb_substr($str, 0, $length, 'utf-8'); } elseif ( function_exists('iconv_substr') ) { $newstr = iconv_substr($str, 0, $length, 'utf-8'); } else { //$newstr = trim_right(substr($str, 0, $length)); $newstr = substr($str, 0, $length); } if ($append && $str != $newstr) { $newstr .= $append; } return $newstr; }
PHP版本,从7.1升级到7.2
当传递一个无效参数时,count()函数将抛出warning警告:
之前版本写法
<?php count(''); // Warning: count(): Parameter must be an array or an object that implements Countable
在7.2版本中将严格执行类型区分,参数类型不正确,将会出现警告,所以需要在使用count方法时注意参数的值,不过也可以通过自己修改方法来替代(不建议):
<?php function func_new_count($array_or_countable,$mode = COUNT_NORMAL){ if(is_array($array_or_countable) || is_object($array_or_countable)){ return count($array_or_countable, $mode); }else{ return 0; } }
<?php $str="test1"; $im = imagecreatefrompng("test.png"); $srcW=ImageSX($im); $srcH=ImageSY($im); $str_width = imagettfbbox(9, 0, "tahoma.ttf", $str); $ni=imagecreatetruecolor($str_width[2] - $str_width[0] + $srcW, $srcH); imagefill($ni, 0, 0, imagecolorallocate($ni, 255, 255, 255)); imagecopyresampled($ni,$im, abs($str_width[2] - $str_width [0]),0,0,0,$srcW,$srcH,$srcW,$srcH); $color = imagecolorallocate($ni, 0, 0, 0); imagettftext($ni, 9, 0, 0, abs($str_width[7] - $str_width[1]), $color, "tahoma.ttf", $str); imagepng($ni, "test1.png"); imagedestroy($ni);
直接在后面加上另一个orderBy User::orderBy('name', 'DESC') ->orderBy('email', 'ASC') ->get(); sql语句效果: SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
laravel模型中打印sql语句 模型中有个 ->toSql() 可以打印sql语句
$goodsShow = Goods::where('cate_id','=',$cate_id) ->where(function($query){ $query->where('status','<','61') ->orWhere(function($query){ $query->where('status', '91'); }); })->first();
where cate_id = $cate_id AND (status < 61 OR status = 91)
var url = "http://localhost:8080/pp?a=1&b="+ paramUrl, var paramUrl = "http://localhost:8080/aa?a=1&b=2&c=3"; 应该使用encodeURIComponent()进行转码 encodeURIComponent(paramUrl) --> http://localhost:8080/pp?a=1&b=http%3A%2F%2Flocalhost%3A8080%2Faa%3Fa%3D1%26b%3D2%23%26c%3D3
encodeURIComponent 和 decodeURIComponent
encodeURIComponent() 用于参数的传递,参数包含特殊字符可能会造成间断。
小程序 undefined is not an object evaluating 't.id';
onLoad: function onLoad(option={}) {
.setData(
微信官方SDK在PHP7中提示:mcrypt_module_open() is deprecated,mcrypt已被OPENSSL代替 具体修改如下
1:WXBizDataCrypt.php
public function decryptData( $encryptedData, $iv, &$data ) { if (strlen($this->sessionKey) != 24) { return ErrorCode::$IllegalAesKey; } $aesKey=base64_decode($this->sessionKey); if (strlen($iv) != 24) { return ErrorCode::$IllegalIv; } $aesIV=base64_decode($iv); // $aesCipher=base64_decode($encryptedData); $aesCipher=$encryptedData; $pc = new Prpcrypt($aesKey); $result = $pc->decrypt($aesCipher,$aesIV); var_dump($result); if ($result[0] != 0) { return $result[0]; } $dataObj=json_decode( $result[1] ); if( $dataObj == NULL ) { return ErrorCode::$IllegalBuffer.'--'; } if( $dataObj->watermark->appid != $this->appid ) { return ErrorCode::$IllegalBuffer.';;'; } $data = $result[1]; return ErrorCode::$OK; }
/** * 对密文进行解密 * [@param](https://my.oschina.net/u/2303379) string $aesCipher 需要解密的密文 * [@param](https://my.oschina.net/u/2303379) string $aesIV 解密的初始向量 * [@return](https://my.oschina.net/u/556800) string 解密得到的明文 */ public function decrypt( $aesCipher, $aesIV ) { try { // $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); // mcrypt_generic_init($module, $this->key, $aesIV); // //解密 // $decrypted = mdecrypt_generic($module, $aesCipher); // mcrypt_generic_deinit($module); // mcrypt_module_close($module); $decrypted = openssl_decrypt($aesCipher,'AES-128-CBC',$this->key,OPENSSL_ZERO_PADDING,$aesIV); // var_dump($decrypted); } catch (Exception $e) { return array(ErrorCode::$IllegalBuffer, null); } try { //去除补位字符 $pkc_encoder = new PKCS7Encoder; $result = $pkc_encoder->decode($decrypted); } catch (Exception $e) { //print $e; return array(ErrorCode::$IllegalBuffer, null); } return array(0, $result); }