当前位置 : 主页 > 网页制作 > html >

利用跨域实现天气预报

来源:互联网 收集:自由互联 发布时间:2021-06-12
1 !DOCTYPE html 2 html lang="en" 3 head 4 meta charset="UTF-8" 5 meta name="viewport" content="width=device-width, initial-scale=1.0" 6 meta http-equiv="X-UA-Compatible" content="ie=edge" 7 titleDocument/title 8 /head 9 style 10 table{ 11 b
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 7     <title>Document</title>
 8 </head>
 9 <style>
10 table{
11     border:1px red solid;
12     border-collapse: collapse;
13     margin:10px 2px;
14 }
15 td{
16     border: 1px black solid;
17     padding: 10px;
18 }
19 
20 </style>
21 <body>
22         <input type="text" id="city">
23         <input type="button" value="天气预报" id="btn">
24         
25         <table id="showTable">
26          
27         </table>
28         
29     <script>
30         var cityObj = document.getElementById(‘city‘);
31         var btnObj = document.getElementById(‘btn‘);
32         var headObj = document.querySelector(‘head‘);
33         var tableObj = document.getElementById(‘showTable‘);
34         //天气预报绑定事件
35         btnObj.onclick = function(){
36             var city = cityObj.value;
37             let url = "http://api.jisuapi.com/weather/query?callback=managerData&appkey=3fa977031a30ffe1&city="+city;
38             var scr = document.createElement(‘script‘);
39             scr.src = url;
40             headObj.appendChild(scr);
41         }
42         //设置回调函数,接受数据
43         function managerData(data){
44             let res = data.result;
45             var str = `<tr><td>城市</td><td>${res.city}</td></tr><tr><td>日期</td><td>${res.date}</td></tr><tr><td>天气</td><td>${res.weather}</td></tr><tr><td>气温</td><td>${res.temp}</td></tr><tr><td>最高气温</td><td>${res.temphigh}</td></tr><tr><td>最低气温</td><td>${res.templow}</td></tr><tr><td>更新时间</td><td>${res.updatetime}</td></tr>`;
46             tableObj.innerHTML = str;
47             console.log(data.result); 
48         }
49     </script>
50 </body>
51 </html>
网友评论