ajax获取当前城市天气情况

  • 最进项目用到了天气的功能,经过不懈的努力终于有了一点收获,特此发上来与大家共享


js脚本

<script type="text/javascript">$(document).ready(function(){//得到当前地址$.getScript("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js",function(){//天气请求ajax$.ajax({url:'customer/weather.htm',     //发送路径type:"post",        //发送方式async:true,        //true异步   false同步  data:{            //参数类型json  data   address:remote_ip_info.city},dataType:"text",  //返回类型success:function(data){document.getElementById("weather").innerHTML=data;}});});});$("#weatherButton").click(function(){//天气请求ajax$.ajax({url:'customer/weather.htm',     //发送路径type:"post",        //发送方式async:true,        //true异步   false同步  data:{              //参数类型json  data   weatheraddress:"苏州"},dataType:"text",  //返回类型success:function(data){alert(data);}});});</script>

Controller

@RequestMapping("weather")public void weather(HttpSession session,HttpServletResponse response,@RequestParam("address") String address) throws Exception{String city_url = URLEncoder.encode(address, "GBK");    //  原GBK  定义需要获取天气信息的城市和编码格式 String link="http://php.weather.sina.com.cn/xml.php?city="+city_url+"&password=DJOYnieT8234jlsK&day=0";  //气象台接口地址URL url;  //声明地址对象try {  url = new URL(link);  //生成urlWeatherUtil parser = new WeatherUtil(url);  //将url交给工具类处理返回天气信息String[] nodes = {"city","status1","temperature1","status2","temperature2"};  //定义一个接受天气信息的字符串数组Map<String, String> map = parser.getValue(nodes);                             //天气信息转换为Map对象String weather=map.get(nodes[0])+" 今天白天:"+map.get(nodes[1])+" 最高温度:"+map.get(nodes[2])+"℃ 今天夜间:"+map.get(nodes[3])+" 最低温度:"+map.get(nodes[4])+"℃ "; //便利数据生成信息字符串System.out.println(address+":"+weather);  response.setCharacterEncoding("utf-8");  response.getWriter().println(weather);  //使用AJAX将天气信息返回session.setAttribute("weather", weather);   //防止丢失将天气信息同时放入session中} catch (MalformedURLException e) {  e.printStackTrace();  }  }

工具类

package com.ambow.invoic.utils;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;public class WeatherUtil {InputStream inStream;  Element root;  public InputStream getInStream() {  return inStream;  }  public void setInStream(InputStream inStream) {  this.inStream = inStream;  }  public Element getRoot() {  return root;  }  public void setRoot(Element root) {  this.root = root;  }  public WeatherUtil() {  }  /** * 通过输入流来获取新浪接口信息 * @param inStream */  public WeatherUtil(InputStream inStream) {  if (inStream != null) {  this.inStream = inStream;  DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();  try {  DocumentBuilder domBuilder = domfac.newDocumentBuilder();  Document doc = domBuilder.parse(inStream);  root = doc.getDocumentElement();  } catch (ParserConfigurationException e) {  e.printStackTrace();  } catch (SAXException e) {  e.printStackTrace();  } catch (IOException e) {  e.printStackTrace();  }  }  }  public WeatherUtil(String path) {  InputStream inStream = null;  try {  inStream = new FileInputStream(path);  } catch (FileNotFoundException e1) {  e1.printStackTrace();  }  if (inStream != null) {  this.inStream = inStream;  DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();  try {  DocumentBuilder domBuilder = domfac.newDocumentBuilder();  Document doc = domBuilder.parse(inStream);  root = doc.getDocumentElement();  } catch (ParserConfigurationException e) {  e.printStackTrace();  } catch (SAXException e) {  e.printStackTrace();  } catch (IOException e) {  e.printStackTrace();  }  }  }  public WeatherUtil(URL url) {  InputStream inStream = null;  try {  inStream = url.openStream();  } catch (IOException e1) {  e1.printStackTrace();  }  if (inStream != null) {  this.inStream = inStream;  DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();  try {  DocumentBuilder domBuilder = domfac.newDocumentBuilder();  Document doc = domBuilder.parse(inStream);  root = doc.getDocumentElement();  } catch (ParserConfigurationException e) {  e.printStackTrace();  } catch (SAXException e) {  e.printStackTrace();  } catch (IOException e) {  e.printStackTrace();  }  }  }  /** *  * @param nodes * @return 单个节点多个值以分号分隔 */  public Map<String, String> getValue(String[] nodes) {  if (inStream == null || root==null) {  return null;  }  Map<String, String> map = new HashMap<String, String>();  // 初始化每个节点的值为null  for (int i = 0; i < nodes.length; i++) {  map.put(nodes[i], null);  }  // 遍历第一节点  NodeList topNodes = root.getChildNodes();  if (topNodes != null) {  for (int i = 0; i < topNodes.getLength(); i++) {  Node book = topNodes.item(i);  if (book.getNodeType() == Node.ELEMENT_NODE) {  for (int j = 0; j < nodes.length; j++) {  for (Node node = book.getFirstChild(); node != null; node = node.getNextSibling()) {  if (node.getNodeType() == Node.ELEMENT_NODE) {  if (node.getNodeName().equals(nodes[j])) {  String val = node.getTextContent();  String temp = map.get(nodes[j]);  if (temp != null && !temp.equals("")) {  temp = temp + ";" + val;  } else {  temp = val;  }  map.put(nodes[j], temp);  }  }  }  }  }  }  }  return map;  }  }

ajax获取当前城市天气情况相关推荐

  1. Python爬虫系列:使用selenium+Edge查询指定城市天气情况

    首先发个福利,有个网店正在推出特价优惠<Python程序设计开发宝典>,原价69.0元,特价46.92元,详情查看:https://detail.tmall.com/item.htm?id ...

  2. Python群机器人发送城市天气情况

    方法1:获取页面HTML内容,再通过正则表达式来获取需要的内容 #!/usr/bin/env python #coding=gbk import requests import urllib.requ ...

  3. 【爬虫实践】获取某城市天气数据

    功能需求 获取山东济南城市每天的天气情况. 需要获取四个数据:天气.温度.风向.风级. url地址:http://www.weather.com.cn/weather/101120101.shtml ...

  4. Python爬取高德地图各城市天气情况

    先上效果图 再上完整代码 import timeimport requests from prettytable import PrettyTable #用来打印表格的库 ''' 查询当前地点天气的u ...

  5. 微信小程序----map组件实现(获取定位城市天气或者指定城市天气数据)

    效果图 实现原理 采用高德地图微信小程序开发API(getWeather),如果 city 属性的值为空(或者没有city属性),默认返回定位位置的天气数据:如果 city 不为空,则返回 city ...

  6. (包教包会)使用网络爬虫的方式获取国内376个城市的每日天气情况,并实现自动给自己发邮件

    主要功能 选择全国376个城市为样本,使用网络爬虫的方式从"天气网"(http://www.weather.com.cn)快速获取当日的天气情况,并实现自动化给自己邮箱发送统计结果 ...

  7. 智能聊天功能——天气情况篇

    天气预报已然成为人们生活中不可缺少的一部分,实时了解气象的优劣,做到第一时间预防是至关重要的.所以,当我们需要外出时,如果能提前知道天气的变化情况,做好预防准备措施,就能让出行变得更加顺利. 本系统为 ...

  8. python也可以成为贴心小管家--每日播报考研倒计时、天气情况、还有“营养鸡汤”

    文章目录 一.前言 二.需要导入的库 三.分析 1.考研倒计时 2.天气情况 3.营养鸡汤 四.完整代码 五.Blogger's speech 一.前言 对于考研,你还在每天数着还有多少天吗?对于天气 ...

  9. Python贴心小管家源代码--每日播报高考倒计时、天气情况、还有“营养鸡汤”

    对于高考,你还在每天数着还有多少天吗?对于天气,你还每天去看天气预报吗?你每天需要看一些励志话语来督促自己前进吗? python可以合上述三者为一体帮你轻松实现你的日常! 运行截图: 很多人学习pyt ...

最新文章

  1. 50倍时空算力提升,阿里云RDS PostgreSQL GPU版本上线
  2. Jmeter调用自定义jar包
  3. java解非线性方程组_Scipy - 非线性方程组的所有解
  4. weka不能使用Apriori/FPGrowth
  5. Spring-Cloud中的 熔断、限流、降级
  6. Redis中的哨兵机制的不足
  7. java定位线程阻塞_Arthas - 定位 Java 性能问题原来这么简单
  8. React开发(115):子组件无法处理复杂的数据格式
  9. java openmp库_OpenMP的环境变量及库函数
  10. 2.24. Spring boot with Apache Kafka
  11. 比特币的密钥、地址、钱包
  12. 02.XMemcached的使用
  13. codesys编程_CODESYS楼宇自动化应用案例:化学系教学楼智能排气系统
  14. 分享一个鼠标宏软件(XMouseButtonControl)用于替换logitech option等软件
  15. Unity 实现人物移动
  16. 华为mate40和vivox50pro+哪个好
  17. 圆面积计算公式,这样理解起来超简单!
  18. vue项目实现前端预览word和pdf格式文件
  19. TutorialsPoint NumPy 教程(转)
  20. adb remount 失败

热门文章

  1. js关闭当前窗口刷新父页面
  2. uni-app实现PDF文件下载功能
  3. JAVA面试高频率问题
  4. vs2015中安装Qt环境
  5. 从0到1:微信提现收费的背后
  6. 安装MySQL时出现no compatible servers were found的解决方法
  7. 热烈祝贺黄手艺冒菜景德镇市珠山区陶阳南路东
  8. java 接收json 字符串_spring接收json字符串的两种方式
  9. 中国手机网络制式常识
  10. 总结:linux驱动之I2C至少四种读写方法