微信小程序踩坑日记4——真机端解析json数组和开发平台不一样

0. 引言

  环境:访问服务器端php,获取json数组,并渲染在前台

  问题描述:保证在开发平台上的正常运行,但是在真机端却出现了无法正确解析wx.request()返回的数据(特指无法解析res.data的json数组

1. 解决方案

  保证在开发平台的正确解析

  问题自然而然引向了对string和json之间的转换问题,这里得益于这篇网友的博文

  但是,res.data在开发平台上显示的是object,而在真机端却显示的string,所以我们需要先判断开发平台,在转换类型。

// 查看平台
wx.getSystemInfo({
    success: (res) => {
        console.log("开发平台: " + res.platform);
        that.setData({
            platform: res.platform
        })
    }
})
wx.request({
    url: 'https://xxxx/xxx.php',
    method: "GET",
    dataType: "json",// 推荐加上这一行,虽然是默认值
    header: {
        'content-type': 'application/json'
    },
    success: (res) => {
        let ans = res.data;
        console.log("数据库访问成功")
        if (that.data.platform == "android") {
            let str = ans.replace(/\ufeff/g, "");//去除反斜杠
            ans = JSON.parse(str);//string转object
        }
        // 设置回调函数
        if (this.getGoodListCallback) {
            this.getGoodListCallback(ans)
        }
    },
    fail: (e) => {
        console.log("数据库访问失败")
        console.log(e)
    }
})

猜你喜欢

转载自www.cnblogs.com/Lu-Yuyang/p/11267289.html
今日推荐