微信小程序踩坑日記4——真機端解析json數組和開發平臺不同

0. 引言

  環境:訪問服務器端php,獲取json數組,並渲染在前臺php

  問題描述:保證在開發平臺上的正常運行,可是在真機端卻出現了沒法正確解析wx.request()返回的數據(特指沒法解析res.data的json數組html

1. 解決方案

  保證在開發平臺的正確解析android

  問題天然而然引向了對string和json之間的轉換問題,這裏得益於這篇網友的博文數據庫

  可是,res.data在開發平臺上顯示的是object,而在真機端卻顯示的string,因此咱們須要先判斷開發平臺,在轉換類型。json

 

// 查看平臺
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)
    }
})
相關文章
相關標籤/搜索