微信扫描二维码进入小程序的代码
xuexi 2025-12-02 09:44:19 发表在:JS 查看数:24
  onLoad(query) {
       this.getLocation();//地图
       try {
        // 1. 优化:先判断 query.q 是否存在,再解码(避免 undefined 解码报错)
        const q = query.q ? decodeURIComponent(query.q) : '';
        console.log('二维码原始链接:', q);

        // 2. 校验 URL 有效性(保留你的逻辑,提示语更精准)
        if (!q) {
          wx.showToast({ title: '未获取到有效二维码链接', icon: 'none' });
          return;
        }

        // 3. 核心:解析 code 参数(补充低版本兼容 + 特殊字符解码)
        let code = '';
        if (wx.getQueryString) {
          // 高版本:用内置 API(简洁高效)
          code = wx.getQueryString(q, 'code');
        } else {
          // 低版本 fallback:正则手动解析(兼容所有基础库)
          const reg = new RegExp(`(\\?|&)code=([^&]*)(&|$)`);
          const match = q.match(reg);
          code = match ? decodeURIComponent(match[2]) : ''; // 二次解码特殊字符(如 %20、中文)
        }

        // 4. 新增:校验 code 是否有效(避免空值导致后续逻辑报错)
        if (!code) {
          wx.showToast({ title: '链接中未包含有效 code 参数', icon: 'none' });
          return;
        }

        // 5. 写入数据(保留你的逻辑)
        this.setData({ code });
        console.log('解析成功,code:', code);

        // 后续业务逻辑(如调用接口验证 code)
        // this.verifyCode(code);

      } catch (error) {
        // 新增:捕获解码/解析过程中的异常(如 URL 格式错误)
        wx.showToast({ title: '二维码参数解析失败', icon: 'none' });
        console.error('解析错误详情:', error);
      }

    },
获取则使用
code:this.data.code

code:this.data.code

最近访问时间:2025-12-06 07:35:07
知识库:406条鸣谢:TAY  备案号:蜀ICP备2024090044号-1