调用腾讯天气 qq-weather

252 阅读1分钟

qq-weather

  1. 封装jsonp, 可以做成一个js工具函数
function jsonp(options) {
  // 动态创建script标签
  var script = document.createElement('script')
  // 拼接字符串的变量
  var params = ''

  for (var attr in options.data) {
    params += '&' + attr + '=' + options.data[attr]
  }

  // myJsonp0124741
  var fnName = 'myJsonp' + Math.random().toString().replace('.', '')
  // 它已经不是一个全局函数了
  // 我们要想办法将它变成全局函数
  window[fnName] = options.success
  // 为script标签添加src属性
  script.src = options.url + '?callback=' + fnName + params
  // 将script标签追加到页面中
  document.body.appendChild(script)
  // 为script标签添加onload事件
  script.onload = function () {
    document.body.removeChild(script)
  }
}
  1. 使用jsonp
jsonp({
  url: 'https://wis.qq.com/weather/common',
  data: {
    source: 'pc',
    // weather_type: 'forecast_1h',
    weather_type: 'forecast_1h|forecast_24h|observe',
    province: '江苏省',
    city: '苏州',
  },
  success: function (data) {
   console.log(data);
  },
})
  1. 作为测试
<html>
  <body>
    <div>
      receive <span id="qwerty"> </span>
    </div>
  </body>
  <script>
    function callfun(data) {
      document.getElementById('qwerty').innerHTML = JSON.stringify(data);
    }
  </script>
  <script src="https://wis.qq.com/weather/common?source=pc&weather_type=observe%7Cforecast_1h%7Cforecast_24h%7Cindex%7Calarm%7Climit%7Ctips%7Crise&province=%E6%B1%9F%E8%8B%8F%E7%9C%81&city=%E8%8B%8F%E5%B7%9E%E5%B8%82&county=&callback=callfun"></script>
</html>
  1. 详细解释课参考 [www.zhihu.com/question/19…]