微信小程序onLaunch获取openid,onload中获取不到解决方法

微信小程序云开发之获取用户openid并全局调用 openid,简单来说是用户进入你的小程序的唯一标识,不管用户怎么改名改信息,你都可以通过openid锁定他。因此获取它十分重要。 而微信小程序官方提供了云函数,可以方便我们在用户进入小程序时直接获取它。 具体做法如下: 我们用云开发模板创建小程序项目时,在该目录下有login云函数,我们可以利用它实现获取openid 右键上传并部署,云端安装依赖后 打开app.js,在onLaun... 阅读详情

场景描述: 小程序有3个页面. 分别为 a页面 (首页面), b页面, c页面. 在app.js 中获取 openid, 然后在 其他3个页面中使用.

问题描述: 我们在 app.js 的onLaunch 中获取到 openid, 然后 赋予 app.globalData.openid 中, 但是在 a页面 的 onLoad 中输出app.globalData.openid, 却为空. b页面点击,可以输出,c页面点击,也可以输出.再点击到a页面, 此时也可以输出.

问题分析: 在 app.js中获取openid 是异步的,所以导致,可能执行到的第一个页面 a页面 的 onLoad 时候,openid还没有返回.导致 第一个页面a页面 的 onLoad 中没有获取到 app.globalData.openid

解决方案: 在第一次登录小程序的时候,是没有任何信息的,此时,我们到登录页面登录,登陆之后,有了全局的openid,和缓存openid. 后面我们第二次登陆, 在 a页面(首页吗) 中查看是否存在 缓存openid, 如果不存在,说明客户肯定是第一次登陆.则清除所有的缓存和去全局. 如果存在, 还分为2种情况, 此时需要用 wx.checkSession 来检测是否登录过期,第一种情况, 没有登录过期,则直接使用缓存即可. 第二种情况, 登录过期,则清除所有状态. 后续操作, 都使用全局. 在第一种情况下, 把缓存openid赋值给全局openid. 后续操作也是一样.

思路: 第一次登陆的时候, 存了 缓存openid 后续根据这个来判断 是否登陆过, 如果 缓存openid 存在, 则在根据 wx.checkSession来判断,用户登陆是否过期, 如果没有过期, 则直接使用. 如果过去,清除所有状态. 在其他页面中, 可以直接判断 app.globalData.openid 是否存在,存在表示登录,不存在表示没有登录. 其他页面不用考虑异步的情况.

注意: 这个判断要放在 a页面(首页面) 的 onshow 中, 因为有可能是之前没有登录,后来点击登录了,再点击回来,所以每次都要验证一下. 我们这个首页面的判断, 是针对首页面的,其他页面可以直接通过 缓存或者全局来判断是否登录失效. 我这个项目是3个页面来回切换,所以逻辑判断需要放在 onShow 中执行.

个人显示头像信息页面: 之前的判断去掉, 然后把判断放在 onshow 中. 如下

  onShow: function () {
    
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    }
  },

部分重要代码:

  • 首页面代码
//app.js
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function (options) {

        /**
         * 判断 缓存openid 是否存在
         * 不存在, 说明之前没有登陆过,是第一次登陆, 此时清除所有状态.
         * 存在,分为2种情况,通过 wx.checkSession 来判断
         * 第一种情况, 没有过期, 则直接赋值使用.
         * 第二种情况, 已经过期, 此时清除所有状态.
         */
        if (wx.getStorageSync('openid')) {
            wx.checkSession({
                success: (res) => {
                    //session_key 未过期,并且在本生命周期一直有效, 把之前的缓存赋值给2个全局变量
                    app.globalData.openid = wx.getStorageSync('openid');
                    app.globalData.userInfo = wx.getStorageSync('userInfo');
                    
                    // 获取到 openid,做后续操作.
                },
                fail: (res) => {
                    // session_key 已经失效,需要重新执行登录流程, 清除缓存和全局信息
                    try {
                        wx.removeStorageSync('openid');
                        wx.removeStorageSync('userInfo');
                        app.globalData.openid = '';
                        app.globalData.userInfo = null;

                        // 没有获取到,做后续操作
                    } catch (e) {
                        console.log("清除缓存失败!");
                    }

                },
            })
        } else {
            console.log("没有登录");
            //缓存不存在,清除下所有状态.
            try {
                wx.removeStorageSync('openid');
                wx.removeStorageSync('userInfo');
                app.globalData.openid = '';
                app.globalData.userInfo = null;

                // 没有获取到,做后续操作
            } catch (e) {
                console.log("清除缓存失败!");
            }

        }
    },
...
  • 其他页面
    onShow: function () {
        if(app.globalData.openid){
            console.log('登录');
        }else{
            console.log('没有登录');
        }
    },

全部代码

  • a 页面(首页吗)
// pages/test1/test1.js
//获取应用实例
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        /**
         * 判断 缓存openid 是否存在
         * 不存在, 说明之前没有登陆过,是第一次登陆, 此时清除所有状态.
         * 存在,分为2种情况,通过 wx.checkSession 来判断
         * 第一种情况, 没有过期, 则直接赋值使用.
         * 第二种情况, 已经过期, 此时清除所有状态.
         */
        if (wx.getStorageSync('openid')) {
            wx.checkSession({
                success: (res) => {
                    console.log("登录");
                    //session_key 未过期,并且在本生命周期一直有效, 把之前的缓存赋值给2个全局变量
                    app.globalData.openid = wx.getStorageSync('openid');
                    app.globalData.userInfo = wx.getStorageSync('userInfo');
                    
                    // 获取到 openid,做后续操作.
                },
                fail: (res) => {
                    console.log("登录失败");
                    // session_key 已经失效,需要重新执行登录流程, 清除缓存和全局信息
                    try {
                        wx.removeStorageSync('openid');
                        wx.removeStorageSync('userInfo');
                        app.globalData.openid = '';
                        app.globalData.userInfo = null;

                        // 没有获取到,做后续操作
                    } catch (e) {
                        console.log("清除缓存失败!");
                    }

                },
            })
        } else {
            console.log("没有登录");
            //缓存不存在,清除下所有状态.
            try {
                wx.removeStorageSync('openid');
                wx.removeStorageSync('userInfo');
                app.globalData.openid = '';
                app.globalData.userInfo = null;

                // 没有获取到,做后续操作
            } catch (e) {
                console.log("清除缓存失败!");
            }

        }
        
    },

})
  • 第二个页面, 个人登录页面
//index.js
//获取应用实例
const app = getApp()
const util = require("../../utils/util");

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  bindQuit: function () {
    wx.removeStorageSync('openid');
    wx.removeStorageSync('userInfo');
    app.globalData.openid = '';
    app.globalData.userInfo = null;
    this.setData({
      userInfo: null,
      hasUserInfo: false
    })
  },
  onLoad: function () {

  },
  onShow: function () {

    if (app.globalData.userInfo) {
      console.log("登录");
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    }else{
      console.log("没有登录");
    }
  },

  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo;

    //设置缓存userInfo
    wx.setStorageSync('userInfo', e.detail.userInfo);
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })

    const that = this;
    // 登录
    wx.login({
      success: res => {

        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        const code = res.code;
        const url = app.globalData.httpBase + "/api/xcx/getOpenid?code=" + code;

        util.newhttp(url).then(function (res) {
          const resData = res.data;

          if (resData.code == 1) {
            app.globalData.openid = resData.data.openid;
            wx.setStorageSync('openid', resData.data.openid);

          }
        }).catch(function (error) {
          console.log(error);
        })

      }
    })


  }
})
  • 第三个页面
// pages/test2/test2.js
//获取应用实例
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        if(app.globalData.openid){
            console.log('登录');
        }else{
            console.log('没有登录');
        }
    },

})
小程序 onLaunch 与 onLoad 异步问题的解决方案 在小程序中,我们一般在onLaunch中发起登录请求,由于是请求是异步的,在onLoad之后才执行完登录请求,如果在onLoad中需要使用请求后的数据,会发现取不到值,以下是一些解决方式,可以按自己所需使用。 使用回调函数 // app.js onLaunch () { wx.login({ success: result => { wx.request({ url: 'test.php' // 示例 data: {...}, success: res =&. 阅读详情

相关推荐

uniapp写微信小程序,获取openId、unionId

使用uniapp写微信小程序,获取openId,获取unionId

m0_56597737的博客 9853

小程序开发学习记录-获取用户openid

主要功能:小程序获取用户的openid,作为用户唯一识别码。 功能说明:之所以要获取用户的openid是因为其具有唯一识别性,用做识别用户的唯一标识。有了唯一标识我们才能知道是谁用了我们的小程序。而微信制定的规矩使得小程序无法直接获得用户的openid,需要通过云开发模式的接口或者我们自己的服务器作为中转,向微信发起请求来获得。 虽然微信希望我们能获得唯一识别码和sessionkey后结合项目生成自定义登录态(比如独立于微信的账号密码用来登录),但我的小程序目前涉及不到这个功能,只是想学习小程序的开..

随缘发 880

【低空经济】无人机充电站设计方案

随着无人机技术的快速发展和广泛应用,其在物流、农业、巡检、救援等领域的应用日益普及。然而,无人机的续航能力一直是限制其大规模应用的关键因素之一。为了解决这一问题,无人机充电站的设计与建设显得尤为重要。本项目旨在设计一套高效、智能、可扩展的无人机充电站系统,以满足不同场景下无人机的充电需求,提升其作业效率和应用范围。无人机充电站的设计将围绕以下几个核心目标展开:首先,充电站应具备快速充电能力,以减少无人机的停机时间,提高作业效率;

2959

小程序中onLuanch()与页面onLoad()问题

小程序中在App.js获取用户数据并赋值到全局变量 在index.js页面中,会发现第一次加载的全局变量是空的,要到第二次才会加载出来,这是因为在小程序中onLaunch()函数加载要比页面的onload()函数要慢。 解决方法: 1:使用promise异步解决这个问题 2:更改页面的逻辑 ...

qq_44468494的博客 715

STM32CubeMX平台F4系列固件下载核心要点

详解STM32CubeMX平台下F4系列单片机的固件包下载方法与常见问题,重点讲解stm32cubemx固件包下载流程及配置技巧,帮助开发者快速完成开发环境搭建。

weixin_42575505的博客 891

(第100天)Oracle GoldenGate 常见故障处理指南

OGG 运维的核心在于细致的配置管理和主动的问题排查。熟悉常见错误、掌握关键操作流程、并善用日志和调试工具,是保障数据同步任务稳定运行的关键。希望这份指南能帮助您更高效地解决 OGG 同步中遇到的问题。祝您运维顺利!

LuciferLiu_DBA 301

微信小程序分享后真机参数获取不到和部分参数不能获取问题问题解决

微信小程序的很多API,都是BUG,近期开发小程序就遇到了分享后开发工具可以获取参数,但是真机怎么都拿不到参数的问题。使用 getCurrentPages()[0].options 方法获取 options 对象。再从options 对象中获取,path路径的参数。在onLoad(options) 中。

Qensq的博客 4098

SAP 标准 CDS View 到底能不能用 CDS Extension View 扩展,我们在项目里应该这样判断

文章摘要:判断SAP标准CDS视图(如A_PRODUCT)能否扩展字段,不能仅凭命名或@Metadata.allowExtensions判断,需检查DDL源码中的@AbapCatalog.viewEnhancementCategory值。#PROJECTION_LIST允许扩展字段,#NONE则禁止。聚合视图需额外包含#GROUP_BY,UNION视图需#UNION。CDS View Extension用于新增字段,Metadata Extension仅用于添加注解。在ABAP Cloud环境中还需检查AP

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 99

微信小程序异步调用app函数 解决别的页面onload获取不到app onlaunch中set的openid问题

先在app.js中自定义一个函数 内容写自己需要传的数据,我这里需要的是用户的openid lc: function (wei) { var that = this; wx.login({ success: function (res) { console.log(res.code) //发送请求 wx.reques...

weixin_40938312的博客 1222

破晓之光:GTK#框架让C# WinForm程序跨平台运行的终极指南

GTK#框架的出现,彻底打破了C# WinForm只能在Windows上运行的桎梏。

墨夶的博客 604

AM芯片性能测试

目前车载FM&AM没有明确的国标,因此各家测试项目可能不同,最主要测试标准比较混乱,多是根据具体芯片的规格书以及与芯片厂商协商。信号发生器:R&S SMCV100B音频分析仪:R&S UPV AUDIO AYALYZER DC 250KHZ(AP的也可以)专用USB-I2C控制模块(不同芯片控制模块不同,例如SPI或UART的控制模块)卡农线(针对模拟声道输出,+接左/右声道,-接GND,地可接GND也可悬空)

qflook的博客 902

微信小程序页面onLoad获取app.js的onLaunch数据(异步获取用户信息)

onLoad和onLaunch异步执行时,如何获取并建立联系

一出好剧 4365

17.6 LangSmith 私有化部署实战指南:企业级AI应用的安全基石

LangSmith 私有化部署, 企业级AI开发平台, 数据隐私合规, 混合云架构, 模型监控与审计。

yonggeit的博客 3777

解决微信小程序onLaunch与onload执行顺序问题

问题产生: 准备使用微信小程序去获取openid,把获取openid的代码写在app.js的onlaunch中。想在后续的页面中使用openid,结果在页面中打印出来显示是和预期的不太一样: // APP.JS var ApiList = require('utils/api.js'); App({ onLaunch: function () { // // 展示本地存储能力 ...

奇葩也是花 8179

Cloud Connector RFC 访问控制深度实践:为 SAP BTP ABAP environment 打通安全、可控的远程连接

本文是一份面向企业ABAP团队与平台工程团队的Cloud Connector RFC访问控制配置指南。文章详细介绍了虚拟主机/实例号、负载均衡、资源白名单等核心概念,并提供了从零开始的配置流程。主要内容包括:通过Cloud Connector建立安全隧道的价值(零暴露、最小权限)、两种连接类型(无负载均衡/带负载均衡)的配置方法、资源白名单设置技巧,以及两个典型应用场景(Custom Code Migration远程检查与BAPI调用)的实操案例。指南基于SAP官方文档,包含落地经验与避坑建议,可帮助团队快

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 146

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

小程序onLaunch 与 onload 的异步问题解决方案

微信小程序app.js 中 onLaunch 与 index.js 中 onload 的异步执行问题 , 在同时触发的情况下 如何等待返回值而响应index中 onload的内容 比如说 获取用户的openid或者凭证 在没返回需要的数据之前 index.js 的 onload会执行 从而导致后续的代码没有openid的支持 * ES6中提供了一个promise方案是一个不错的解决方案...

一个天秤座的程序猿???? 8672

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

小程序onLaunch 与 onload 的异步问题(微信,支付宝实测可用)

小程序app.js 中 onLaunch 与 index.js 中 onload 的异步执行问题 , 在同时触发的情况下 如何等待返回值而响应index中 onload的内容 比如说 获取用户的openid或者凭证 在没返回需要的数据之前 index.js 的 onload会执行 从而导致后续的代码没有openid的支持 * ES6中提供了一个promise方案是一个不错的解决方案 promi...

XinYe666666的博客 1199

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

微信小程序onLaunch异步,首页onLoad先执行?

本来按照事件顺序,小程序初始化时触发App里的onLaunch,后面再执行页面Page里的onLoad,但是在onLaunch里请求获取是否有权限,等待返回值的时候Page里的onLoad事件就已经执...

qq_29069777的博客 172

onlaunch 异步_小程序onLaunch 与 onload 的异步问题(微信,支付宝实测可用)

小程序app.js 中 onLaunch 与 index.js 中 onload 的异步执行问题 , 在同时触发的情况下 如何等待返回值而响应index中 onload的内容比如说 获取用户的openid或者凭证 在没返回需要的数据之前 index.js 的 onload会执行 从而导致后续的代码没有openid的支持 *ES6中提供了一个promise方案是一个不错的解决方案promise下载地...

weixin_39901077的博客 367

axions获取到值赋值不到data中_微信小程序请求获取openid实现登录的"坑"...

首先我们需要获取到用户的openid:onLaunch:function(){ wx.login({ success: function (res) { wx.request({ url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + d.ID + '&secret=' + d...

weixin_39970064的博客 358

微信小程序--自带云服务器获取openid

获取openid 简介:使用微信小程序本身的云服务器获取openid 第一步,app.js中的onLaunch方法里面加入: if (!wx.cloud) { console.error('请使用 2.2.3 或以上的基础库以使用云能力') } else { wx.cloud.init({ traceUser: true, }) } 第二步,在需要获取openid的地方调用下面的方法 onGetOpenid: function() {

wy313622821的博客 860

微信小程序获取openid

微信小程序一般要用到openid是在需要到支付接口调用时用到,比如获取签名的时候就要用到,我们可以在全局app.js里面获取得到,然后给其它页面调用,具体步骤如下: 1.我们进到app.js里面获取,生命周期函数的执行都会先执行app.js里面的onlaunch()方法,让每次用户进入到页面时先获取到它的openid,获取代码如下: //app.js const { host, } = ...

javascript和jq设置金额整数与小数点后面的字体大小 432

微信小程序 onLaunch request=>success 再执行page onload

onLaunch: function () { console.info("onlaunch"); var that = this; // 登录 wx.login({ success: res =&gt; { wx.request({ url: 'test', success: function ...

zjy660358的专栏 2994

微信小程序云开发获取用户openid

新建目录起名自定义,我起名是cloudFun 然后再project.config.json里面配置云环境“cloudfunctionRoot”:"./cloudFun" 保存后文件夹那里后面会出现云环境名称云环境的图标 在此文件上右键新建Node.js云函数login ...

2630

uni-app 中利用 Promise 实现 onLaunch 异步回调后执行 onLoad

uni-app 中利用 Promise 实现 onLaunch 异步回调后执行 onLoad

haplant的专栏 775

微信小程序 async await解决异步问题

小程序大部分函数和数据库操作都是异步执行的,如果希望同步执行,需要用到async 和await这对基友,必须成对出现。

oldcoder2000的博客 5472
上一篇: mysql高级-笔记整理
下一篇: 全方位入门git
自娱自乐22
博客等级 码龄18年 241粉丝 135原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值