2025年9月

<script type="text/javascript">
            // 模拟一个异步函数,返回一个 Promise,最终解析出某个值,比如用户ID
            function fetchData() {
              return new Promise((resolve, reject) => {
                  //发动网络请求
                  //成功回调 resolve(userId);
                  //失败回调 reject(res);
                // 模拟异步操作,比如网络请求
                setTimeout(() => {
                  const userId = 12345; // 假设我们从某处获取到了用户ID
                  console.log('fetchData 执行完成,得到 userId:', userId);
                  resolve(userId); // 返回的值可以被下一个 .then() 接收
                }, 1000); // 模拟1秒延迟
                //请求出错
                //reject(res);
              });
            }

            // 模拟另一个异步函数,需要使用上一个函数的结果
            function processData(userId) {
              return new Promise((resolve, reject) => {
                setTimeout(() => {
                  console.log('processData 执行,处理的 userId 是:', userId);
                  const result = `用户 ${userId} 的数据处理完成`;
                  resolve(result); // 最终结果
                }, 1000);
                //请求出错
                //reject(res);
              });
            }

            // 使用 Promise 链式调用
            //fetchData().then((userId) => {return processData(userId);}).then((finalResult) => { console.log('最终结果:', finalResult);}).catch((error) => { console.error('出错了:', error);});

            //语法糖形式
            async function main() {
              try {
                const userId = await fetchData();         
                const finalResult = await processData(userId);  
                console.log('最终结果:', finalResult);
              } catch (error) {
                console.error('出错了:', error);
              }
            }

            // 调用主函数
            main();
</script>

 // 获取access_token
    private function getAccessToken($url, $header)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        return curl_exec($curl);
    } 
  // 微信授权登录
 function wxAuthLogin()
    {
       // $param = $this->request->param();
        $code = $this->frparam('code',1,'','POST');
        $appid = 'appid';
        $secret = 'appSecrect';
        $url = "https://api.weixin.qq.com/cgi-bin/token?appid=$appid&secret=$secret&grant_type=client_credential";
        try {
            $header = array('Accept: application/json',);
            // 获取access_token
            $wx_access_token = json_decode($this->getAccessToken($url, $header), true);
 
            $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $wx_access_token['access_token'];
            $data = array('code' => $code); // 请确保$code变量已经定义
            $options = array(
                'http' => array(
                    'header' => "Content-Type: application/json\r\n",
                    'method' => 'POST',
                    'content' => json_encode($data)
                )
            );
            $context = stream_context_create($options);
            $response = file_get_contents($url, false, $context);
            $result = json_decode($response, true);
            if ($result['errcode'] != 0) {
                JsonReturn(["code" => 1, "msg" => '登录失败']);
            }else{
               $tel = $result['phone_info']['phoneNumber'];
               $m = M('member')->find(['tel'=>$w['tel']]);
              if($m){
                  //走登录流程
                  $update['logintime'] = time();
                   M('member')->update(array('id'=>$m['id']),$update);
                   
                   $payload = [
                        'userId' => $m['id'], 
                        'exp' => time() + 60,     // 1小时后过期
                        'tel' => $tel          // 自定义数据
                        ];
                   $userInfo['name']=$m['username'];
                   $userInfo['id']=$m['id'];
                   $userInfo['litpic']=$m['litpic'];
                   $token =TokenManager::generateToken($payload);
                  
                   JsonReturn(['code'=>0,'msg'=>'登录成功!','token'=>$token,userInfo=>$userInfo]);
               }else{
                   //新增用户
                     //$w['username'] = getRandChar(6);
                     $w['username'] = '微信用户';
                    $w['tel'] = $tel;
                    $w['gid'] = 1;
                    $w['litpic'] = 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132';
                    $w['regtime']=time();
                    $r = M('member')->add($w);  
                    if($r){
                        //走登录流程
                       $payload = [
                            'userId' => $r['id'], 
                            'exp' => time() + 60,     // 1小时后过期
                            'tel' => $tel          // 自定义数据
                            ];
                       $userInfo['name']=$w['username'];
                       $userInfo['id']=$r['id'];
                       $userInfo['litpic']=$w['litpic'];
                       $token =TokenManager::generateToken($payload);
                       JsonReturn(['code'=>0,'msg'=>'登录成功!','token'=>$token,userInfo=>$userInfo]); 
                            
                        
                    }
               }

              
            }
           

        } catch (Exception $exception) {
            return json(["code" => 0, "msg" => $exception->getMessage()]);
        }
    }

时间紧、面向现代用户:选 loading=lazy。

需全兼容或复杂效果:用 lazyload 插件。

折中方案:用 loading=lazy 为主,针对不支持的浏览器引入轻量级插件:

<script>
if ('loading' in HTMLImageElement.prototype === false) {
  var script = document.createElement('script');
  script.src = 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.2/lazysizes.min.js';
  document.body.appendChild(script);
}
</script>
<img src="your-image.jpg" alt="示例图片" loading="lazy" class="lazyload">