一个获取天气预报数据的小案例
HTML代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <style type="text/css"> .school{ background-color: azure; width: 250px; height: 130px; padding: 5px; } .student{ background-color:coral; width: 250px; height: 60px; padding: 5px; } </style> <script src="./js/react.js"></script> <script src="./js/react-dom.js"></script> <script src="./js/babel.min.js"></script> <script src="./js/jquery.min.js"></script> <script src="./js/AjaxApp2.js" type="text/babel"></script> <script src="./js/MyWeather.js" type="text/babel"></script> <body> <div id="app">111</div> <script type="text/babel"> ReactDOM.render( <AjaxApp2/>, document.getElementById("app") ); </script> </body> </html>
java代码:
package com.nf.web; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/GetOtherJSON") public class GetOtherJSON extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //javascript默认取不了跨域的json,但是java的httpURLConnection是可以的 String url_str = "http://www.weather.com.cn/data/cityinfo/101010100.html"; //url_str= url_str+"?city="+URLEncoder.encode("南宁", "UTF-8"); System.out.println(url_str); //new一个URL路径 URL url = new URL(url_str); HttpURLConnection conn = null; conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("GET"); conn.setUseCaches(false);//为了防止访问脏数据 //第一步:上传参数(可以没有) /* OutputStream os = conn.getOutputStream();//获取一个输出流 DataOutputStream dos = new DataOutputStream(os); dos.writeBytes("city="+URLEncoder.encode("北京", "UTF-8")); dos.flush(); dos.close(); */ //第二步,开始下载对方服务器影响的内容 if( conn.getResponseCode()==HttpURLConnection.HTTP_OK){ System.out.println("访问远程服务器正常"); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is,"UTF-8"); BufferedReader br = new BufferedReader(isr); String result = ""; String readOneLine = null; StringBuffer sb = new StringBuffer(); while((readOneLine=br.readLine())!=null){ sb.append(readOneLine); } result = sb.toString(); System.out.println("对方服务器响应的内容:"+result); br.close(); isr.close(); is.close(); conn.disconnect(); /*以下6行代码复制粘贴进来就可以了*/ response.setContentType("text/json;charset=UTF-8;pageEncoding=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); //浏览器和缓存服务器都不应该缓存页面信息 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); PrintWriter out = response.getWriter(); out.print(result); }else{ System.out.println("访问远程服务器有异常:"+conn.getResponseCode()); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
js代码:AjaxApp.js:
var AjaxApp2 = React.createClass({ getInitialState:function(){ return{ cityName:'loding...', temp1:'loding', temp2:'loding', img1:'loding.gif', img2:'loding.gif', ptime:'loding' } }, componentDidMount:function(){ $.ajax({ //url:'test.json', url:'GetOtherJSON', type:'GET', //data:{'city':'北京'}, dataType:'json', timeout:4000, success:function(result){ //alert(result.weatherinfo); this.setState({ cityName:result.weatherinfo.city, temp1:result.weatherinfo.temp1, temp2:result.weatherinfo.temp2, img1:'http://m.weather.com.cn/img/'+result.weatherinfo.img1, img2:'http://m.weather.com.cn/img/'+result.weatherinfo.img2, ptime:result.weatherinfo.ptime }); }.bind(this), error:function(XMLHttpRequest, textStatus, errorThrown){ alert('服务器忙,请不要说脏话,理论上大家都是文明人'); alert(textStatus+XMLHttpRequest.status); } }); //this.setState({studentName:'张学友'}); }, render:function(){ return <div> <MyWeather cityName={this.state.cityName} temp1={this.state.temp1} temp2={this.state.temp2} img1={this.state.img1} img2={this.state.img2} ptime={this.state.ptime}></MyWeather> </div>; } });
MyWeather.js var MyWeather = React.createClass({ getDefaultProps:function(){ return{ cityName:'加载...', temp1:'loding', temp2:'loding', img1:'loding.gif', img2:'loding.gif', ptime:'loding' } }, render:function(){ return <div className="school"> 城市名字:{this.props.cityName}<br/> 最低温:{this.props.temp1}<br/> 最高温:{this.props.temp2}<br/> <img src={this.props.img1} width="21" height="15"/><br/> <img src={this.props.img2} width="21" height="15"/><br/> 最后更新时间:{this.props.ptime} </div>; } });