备注:折线图使用的是 https://www.hcharts.cn/docs/start-helloworld
php代码:
<?php namespace appindexcontroller; use thinkController; use thinkDb; class Exam extends Controller{ //页面展示 public function index(){ return view(); } //请求天气预报 public function weather_do(){ $city = input('get.city'); $redis = new Redis();//实例化redis $redis->pconnect('127.0.0.1','6379');//连接redis $data = $redis->get('weather_'.$city);//获取天气的值 if($data){ //有值 echo $data; }else{ //没有值 //接收传值 $url = "http://api.map.baidu.com/telematics/v2/weather?location=".$city."&output=json&ak=1a3cde429f38434f1811a75e1a90310c"; $data = file_get_contents($url); $redis->set('weather',$data); echo $data; } } }
html代码:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <input type="text" name="city" id="city" placeholder="请输入城市"/> <!-- 图表容器 DOM --> <div id="container" style=" 600px;height:400px;"></div> <!-- 引入 highcharts.js --> <script src="http://cdn.hcharts.cn/highcharts/highcharts.js"></script> <script src="__STATIC__/jq.js"></script> <script> //绑定失去焦点事件 $("#city").blur(function(){ //获取文本框的值 var city = $(this).val(); if(city==""){ alert("城市不能为空");return; } if(city.length>30){ alert("长度不能大于30");return; } var reg = /^[d|a-z|u4e00-u9fa5]+$/; if(reg.test(city)){ //去后台调取接口 $.ajax({ url:"{:url('Exam/weather_do')}", type:"get", dataType:"json", data:{ city:city }, success:function(data){ var x = []; var y_max = [];//最高温度 var y_min = [];//最低温度 //循环拿到date数据,放进一个数组里面 $.each(data.results,function(k,v){ x.push(v.date); //Y轴需要的数据以摄氏度分割 var tem = v.temperature; var arr = tem.split("℃"); var arr2 = arr[0].split("~"); y_max.push(parseInt($.trim(arr2[0]))); y_min.push(parseInt($.trim(arr2[1]))); }) var options = { title: { text: '温度变化范围' // 标题 }, xAxis: { categories: x // x 轴分类 }, yAxis: { title: { text: '温度变化范围' // y 轴标题 } }, series: [{ // 数据列 name: '最高气温', // 数据列名 data: y_max // 数据 }, { name: '最低气温', data: y_min }] };//配置 var chart = Highcharts.chart('container', options);//初始化 } }); }else{ alert("正则匹配失败");return; } }); </script> </body> </html>