如何利用js用京东万象获得的数据接口获取天气信息并返回json数据

JavaScript08

如何利用js用京东万象获得的数据接口获取天气信息并返回json数据,第1张

刚刚去测试了一下,利用ajax的jsonp(跨域)的时候卡在了一个异常上:Uncaught SyntaxError: Unexpected token :。

这个异常是jd在对于ajax的跨域请求时没有对callback进行处理。所以无法让js获取到正确的json数据。

解决方案(php为例):用curl进行获取,也就是用后端做一次转发操作。jd官方也提供php的SDK。以下是我的jq的ajax代码 仅供参考。

$.ajax({

    url:'https://way.jd.com/showapi/address',

    data: {

        area:'鹿城',

        areaid:'101210710',

        needMoreDay:'0',

        needIndex:'0',

        needAlarm:'0',

        need3HourForcast:'0',

        appkey:'你申请的appkey',

        ajax:1

    },

    type: "GET",

    async:false,

    dataType : "jsonp",

    jsonp:'callback',

    jsonpCallback:"jdwx",//jd返回json未对这个做处理导致js无法获取json

    success: function (json) {

        console.log(json)

    },

    error: function (msg) {

       console.log(msg)

    },

    timeout:3000

})

//这是我以前开发天气wedget的时候写过的代码,原理是连接到yahoo api(返回XML),先用cityCode查国家 然后用woeid查地方,这是测试时写过的代码。Yahoo 天气api 好像一部分收费 最后没用yahoo 用 weatherbug的api 那个代码忘了存在哪里了,如果 非常着急的话在跟我说吧 我给你找找,还有调用api的原理,一般不会直接调用api 因为每个人访问时都调用一次的话系统受不了。最好写个windows service 每个一段时间调用一次api然后以.xml形式存放到一个文件夹,在系统中只调用xml文件就好了。如果api一时访问不到了也不会出问题。

才看到你想要的是前台代码, 这是后台的

private string GetWeather(string cityCode)

{

string weather = string.Empty

if (cityCode == "" || string.IsNullOrEmpty(cityCode)) { cityCode = "seoul"}

XmlDocument document1 = new XmlDocument()

document1.Load("http://query.yahooapis.com/v1/public/yql?q=select * from geo.places where text=" + cityCode + "&format=xml")

XmlNodeList nodes1 = document1.GetElementsByTagName("woeid")

string strWoeid = nodes1[0].InnerText

XmlDocument document = new XmlDocument()

document.Load("http://weather.yahooapis.com/forecastrss?w=" + strWoeid + "&u=c")

XmlNodeList nodes = document.GetElementsByTagName("forecast",

@"http://xml.weather.yahoo.com/ns/rss/1.0")

foreach (XmlNode node in nodes)

{

Console.WriteLine("日期:{0},星期:{1},天气:{2},温度:{3}°C 至 {4}°C",

node.Attributes["date"].InnerText,

node.Attributes["day"].InnerText,

node.Attributes["text"].InnerText,

node.Attributes["low"].InnerText,

node.Attributes["high"].InnerText)

//FToC(int.Parse(node.Attributes["low"].InnerText)),

// FToC(int.Parse(node.Attributes["high"].InnerText)))

// //woeid

// // http://query.yahooapis.com/v1/public/yql?q=select * from geo.places where text="Wonju"&format=xml

}

return weather

}

腾讯位置服务平台提供获取经纬度的接口彩云天气申请开发者api调用对应经纬度的天气状况测试环境选择了自己的iphone上的JSbox来运行一个简单的js脚本://简单思路就是 获取ip再获取天气信息const locationKey = "XXXXXXXXXXXXX"const weatherKey = "XXXXXXXXXXXX"const apiList = {location:"https://apis.map.qq.com/ws"}function getLonLat(){$http.get({url: `${apiList.location}/location/v1/ip?key=${locationKey}`,handler: (resp) =>{let location = resp.data&&resp.data.result&&resp.data.result.locationgetLocation(location)}})}function getLocation(location){$http.get({url: `${apiList.location}/geocoder/v1/?key=${locationKey}&location=${location.lat},${location.lng}`,handler: (resp) =>{var data = resp.data $console.info(data.result.formatted_addresses.recommend) }})}/** * * @param {lat:"",lng:""} location */function getWeather(location){$http.get({url: `${apiList.weather}/${weatherKey}/${location.lng},${location.lat}/weather.json`,handler: (resp) =>{let data = resp.data console.info(data) //运行结果参照彩云天气https://open.caiyunapp.com/%E9%80%9A%E7%94%A8%E9%A2%84%E6%8A%A5%E6%8E%A5%E5%8F%A3/v2.5}})}getLonLat()2|0顿时醒悟写到这其实我只是想测试一下两个接口的基本用法以及可用之处,然后突然想到jsbox里面内置的$location可以直接获取到设备的位置信息,通过这样获取到的位置坐标会比ip的更加精准//根据原生SDK获取手机位置function getPhoneLoc(){$location.fetch({handler: function(resp) {var lat = resp.lat var lng = resp.lng var alt = resp.alt let loc = {lat:lat,lng:lng}getLocation(loc)}})}3|0最后运行结果