评论

【wx.request+PHP】返回Array数组与及json_encode中文转码的处理解决示例

本人开发了一个小程序,需要通过wx.request向php网页端获取数据,而此数据很有需要是Array数组,但若获取回来的是Array不能直接使用的,所以需要经过转码为json才能直接索引使用。

//功能简述:本人开发了一个小程序,需要通过wx.request向PHP网页端获取数据,而此数据很有需要是Array数组,最初找遍了度娘或谷歌均未能解决,
//最后经过仔细阅读开发文档(https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html)后得知,wx.request
//所接收回来的data要经过json_encode转为json才能正确使用。故而才有以下成果。

//此片段是小程序端index.js的代码
Component({
  methods:{
    GetStkData:function(e){
      var that = this;
        wx.request({
          url: 'https://www.yourweb.com/data.php?data=yourdata',//此处是你php网页端获取数据的接口
          success: res =>{
            that.setData({
              stkName : decodeURI(res.data.name),//php端已经进行gbk to utf8,故此处需要decodeURI()解码转义回中文
                     stkPrice : res.data.price //除了中文字码,其它数字、英文字母均不需要使用decodeURI()
            },function(){
              //this is setData callback
            })
          }
        })
    }
  }
)}
//=====================================分界线=======================================//
//此片段是网页端data.php接口代码
<?php
  //用于处理json_encode无法转义中文的解决函数
  function gbk2utf8($data){
      if(is_array($data)){
          return array_map('gbk2utf8', $data);
      }
      return iconv('gbk','utf-8',$data);
  }

  $JsonArr = array(
          'name' =>  "中国移动",
          'price' => "50"
  );
  echo json_encode(gbk2utf8($JsonArr));//此处务必使用json_encode进行转码,否则小程序端返回的就是Array而已,而不是json数据
?>


PS:上述代码为缩简版,本人也是刚接触及开发小程序,避免不了会有bug,敬请谅解!有任何问题可以留言交流指正或求助。



最后一次编辑于  2020-10-31  
点赞 2
收藏
评论
登录 后发表内容