JS获取天气和日期

10 篇文章 0 订阅

获取天气和日期

一、编写目的

​ 因为公司需要设计一个界面用来动态的获取当前天气和当前日期

二、实现

​ JSP代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
		<title>持卡信息</title>
		<script type="text/javascript" src="content/Bootstrap/js/jquery-3.2.1.min.js"></script>
		<style type="text/css">
	#cl{
    width:100%;
    height:auto;;
    /* filter:alpha(opacity=100 finishopacity=50 style=1 startx=0,starty=0,finishx=0,finishy=150) progid:DXImageTransform.Microsoft.gradient(startcolorstr=blue,endcolorstr=white,gradientType=0);
    -ms-filter:alpha(opacity=100 finishopacity=50 style=1 startx=0,starty=0,finishx=0,finishy=150) progid:DXImageTransform.Microsoft.gradient(startcolorstr=blue,endcolorstr=white,gradientType=0); *//*IE8*/	
    background:white; /* 一些不支持背景渐变的浏览器 */  
   /*  background:-moz-linear-gradient(top, blue, rgba(0, 0, 255, 0.5));  
    background:-webkit-gradient(linear, 0 0, 0 bottom, from(#ff0000), to(rgba(0, 0, 255, 0.5)));  
    background:-o-linear-gradient(top, blue, rgba(0, 0, 255, 0.5));  */
}
 .d1{
 	margin-left:496px;
 	margin-top:392px;
	}
.d2{
 	/* background-color:red; */
	}
.d2 hover{
 	background-color:blue;
	}
</style>
</head>
<body>
<div class="gradient" id="cl">
<button onclick="refreshWeather()">点击</button>
<button onclick="tt()">点击2</button>
</div>
	
	
	


</body>
<script>
	//获取本地的天气和日期需要做到两点:1.需要根据浏览器的IP查询所在的城市的名称,2.根据城市名称查询近七天的天气和星期,日期
	var city;
	//方法一:通过js直接获取
	 function  tt(){
		 $.ajax({
		    	url: 'http://pv.sohu.com/cityjson?ie=utf-8',
		    	dataType: "script",
		    	async: false,
		    	success: function(){
		    	         //console.log(returnCitySN);
		    	         city = returnCitySN.cname;
		    	     	//此时city的格式为“湖北省随州市”
		    	         var a = city.indexOf("省",0);
		    	         if(a >= 0){
		    	        	 city = city.substring(a+1);
		    	         }
		    	         console.log(city);
		    	         var url = encodeURI("http://wthrcdn.etouch.cn/weather_mini?city="+city);
		    			    $.get({
		    			        url: url,
		    			        dataType: "json",
		    			        async: false,
		    			        success: function (data) {
		    		        		var todayWeather = data.data.forecast[0];
		    				            //document.getElementById("cl").innerHTML=todayWeather.low; 
		    				        $("#cl").html("城市: "+city+"<br/>日期: "+todayWeather.date+"<br/>"+"温度" +todayWeather.high); 
		    			            
		    			        }
		    			    });
    	        }
    	}); 
		 
	 }
	  //方法二 : 通过java后台发送查询城市请求(解决跨域问题) ,然后通过返回值查询当前城市的天气 
	function refreshWeather() {
	    $.get({
	        url: "weather",
	        dataType:"json",  //数据格式设置为jsonp
	        async: false,
	        success: function (data) {
	        	city = data.city;
	        }
	    });
	   
	    	
	    var url = encodeURI("http://wthrcdn.etouch.cn/weather_mini?city="+city);
	    $.get({
	        url: url,
	        dataType: "json",
	        async: false,
	        success: function (data) {
        		var todayWeather = data.data.forecast[0];
		            //document.getElementById("cl").innerHTML=todayWeather.low; 
		        $("#cl").html("城市: "+city+"<br/>日期: "+todayWeather.date+"<br/>"+"温度" +todayWeather.high); 
	            
	        }
	    });  
	} 
		
</script>

</html>

JAVA代码:

package net.smartschool.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;





@Controller
public class WeatherController {
	
	@RequestMapping(value = "/weather", method = RequestMethod.GET)
	@ResponseBody
	public String getWeather() {
		URL url = null;              
	    BufferedReader in = null;
	    StringBuffer sb = new StringBuffer();   
	    try{
	    	url = new URL("http://ip.ws.126.net/ipquery");      
		    in = new BufferedReader(new InputStreamReader(url.openStream(),"GBK") );   
		    String str = null;
		    while((str = in.readLine()) != null) {  
		    	sb.append(str);
	    	}
	    } catch (Exception e) {  
	    	e.printStackTrace();
        } finally{            
	        if(in!=null) { 
	            try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}     
	        }     
	        
	   }     
       String  data =sb.toString();
       int b = data.indexOf("{");
       String temp = data.substring(b);
       JSONObject json = JSONObject.parseObject(temp);
      // String parString = json.getString("")
       return json.toString();
		
	}

}

三、效果

1560851077942

1560851097111

按钮”点击“和”点击2“分别调用方法2和方法1,但是效果相同。

总结:方法2存在一定的缺陷,那就是定位的天气服务器所在的天气,而不是浏览器所在的天气。

更新时间

2019-08-30

新的通过js直接获取城市的方法

方法一中通过js直接或的城市的方法中的获取天气的接口的返回值发生了改变,新的方法如下

//方法一:通过js直接获取
	 function  tt(){
		 $.ajax({
		    	url: 'http://ip.ws.126.net/ipquery?ie=utf-8',
		    	dataType: "script",
		    	async: false,
		    	success: function(data){
		    	         //console.log(returnCitySN);
		    	        
		    	         var url = encodeURI("http://wthrcdn.etouch.cn/weather_mini?city="+lc);
		    			    $.get({
		    			        url: url,
		    			        dataType: "json",
		    			        async: false,
		    			        success: function (data) {
		    		        		var todayWeather = data.data.forecast[0];
		    		        		var tomorrowWeather = data.data.forecast[1];
		    		        		$("#cweather").html("<div class='text-header'>"+data.data.wendu+"℃"+"</div>"+
		    		        				"<div class='text'>"+lc +"天气:"+todayWeather.type+"</div><div class='text'>今日温度</div>"+
		    		        				
		    		        				"<div class='text'>"+todayWeather.high+todayWeather.low+"</div><div class='text'>明日</div>"
		    		        				+"<div class='text'>"+tomorrowWeather.high+tomorrowWeather.low+"</div>"
		    		        				+"<div class='text'>"+todayWeather.date.substring(todayWeather.date.indexOf("日")+1)+"</div>"
		    		        				); 
		    				       
		    			        }
		    			    });
    	        }
    	}); 
		 
		
		 
	 }

在这里插入图片描述

获取城市接口

1.获取链接:http://whois.pconline.com.cn/ip.jsp

获取城市有关不同形式的接口

下面链接提供不同格式的城市的返回以及城市编码等
参考链接:http://whois.pconline.com.cn/

通知

看到这篇文档的朋友,如果本人提供的接口失效,麻烦在楼下评论告知一下,谢谢!
本片文章如果有帮助到你,麻烦评论点个赞,谢谢!

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值