• 微信小程序踩坑日记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)
        }
    })
  • 相关阅读:
    BZOJ 4503: 两个串 FFT
    [FJOI2014]最短路径树问题
    [JSOI2009]游戏Game
    bzoj 2463 [中山市选2009]谁能赢呢?
    [CQOI2007]余数求和
    [NOI2011]兔兔与蛋蛋游戏
    [HNOI2015]实验比较
    bzoj2125 最短路
    [COGS 2877]老m凯的疑惑
    [HNOI2015]开店
  • 原文地址:https://www.cnblogs.com/Lu-Yuyang/p/11267289.html
Copyright © 2020-2023  润新知