天气预报 - josn格式数据

简爱代码>JavaScript2012-12-29 17:3061063
weather.com.cn API已废,所以代码也就无用了
暂时顶替的 API 的地址: http://gouji.org/api/weather/?city=
支持JSONP 回调函数 为 callback

简易的演示代码 ( js 获取天气数据):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>天气查询</title>
<style>
body {
  width: 400px;
  font-size: 14px;
}
ul {
  list-style: none;
}
</style>
</head>
<body>
  <form onSubmit="return getWeather()">
    <label for="city">城市: </label>
    <input id="city" name="city" type="text" />
    <input id="submit" type="submit" value="提交" />
  </form>
  <ul id="print"></ul>
  <br><a href="http://gouji.org/?post=15">返回</a>
<script type="text/javascript">
var WeatherAPI = 'http://gouji.org/api/weather/',
    JSONP_ING = false
    _button = _$('submit'),
    _putdom = _$('print');

// 获取 天气数据
function getWeather(){
  url = WeatherAPI + '?callback=setWeather&city=' + _$('city').value
  if(!JSONP_ING)
    jsonp(url);
  else
    alert('查询中');
  return false;
}


// 返回数据处理 函数 (未做判断)
function setWeather(d){
  console.log('天气返回');
  w = d.weather,
  l = w.length;
  html = '<li>城市: ' + d.city +'</li><li>日期: '+ d.date +'</li>';
  for(i=0; i<l; i++){
    html += '<li>'+ w[i].date +' '+ w[i].weather +' '+ w[i].wind +' '+ w[i].temp +'</li>'
  }
  _putdom.innerHTML = html;
}


// 算是原始 jsonp 兼容应该没有问题
function jsonp(url) {
  jsonpIng(true);
  var d = document.createElement("script");
  d.src = url;
  d.onload = d.onreadystatechange = function() {
    if (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") {
      jsonpIng(false);
      document.getElementsByTagName("head")[0].removeChild(this);
    }
  };
  document.getElementsByTagName("head")[0].appendChild(d)
}


// ing 状态设置
function jsonpIng(d){
  if(d){
    JSONP_ING = true;
    _button.value = '提交 ing...'
  }else{
    JSONP_ING = false;
    _button.value = '提交'
  }
}


function _$(a){return document.getElementById(a);}
</script>
</body>
</html>


本文出自简爱博客,转载时请注明出处及相应链接。

评论

  1. test2014-12-17 15:58回复

    [抠鼻/]

  2. 测试2012-12-29 20:47回复

    <script>alert("跨站")</script>

    1. 简爱2012-12-29 23:45回复

      @测试:这玩意儿不显示啊 (:

发表评论

电子邮件地址不会被公开。必填项已用*标注