小程序通过IP获取城市

getCity(){
                const _this = this ;
                wx.request({
                    url: 'https://pv.sohu.com/cityjson?ie=utf-8',
                    data: {},
                    header: { 'Content-Type': 'application/json' },
                    success: function (ops) {
                        console.log(ops,'opsssssss')
                        let cname = ops.data ?  ops.data.split('=')[1] : '' ;
                        let splitDoc = cname ? cname.split(';')[0] : '' ;
                        let cityIpInfo = JSON.parse(splitDoc).cname ;
                        _this.cityIpInfo = cityIpInfo.indexOf('市') === -1 ? '未知' : cityIpInfo.split('市')[0];
                        wx.setStorageSync('cityIpInfo',_this.cityIpInfo)
                        
                        if(cityIpInfo.indexOf('市') === -1){
                            _this.areaCode = '' ;
                            wx.setStorageSync('areaCode',false)
                        }
                        
                       
                        console.log(_this.cityIpInfo,'_this.cname--',cname)
                    },
                    fail: function (resq) {
                       console.log(resq)
                    },
                    complete: function () {
                    }
                })
            },

如果Ip自动获取不到,看一下是不是域名限制了,如果不是就手动选择地域详情请看:

https://www.cnblogs.com/panax/p/14464223.html

 

posted @ 2021-03-01 16:31  Panax  阅读(375)  评论(0编辑  收藏  举报