1. 程式人生 > >angularjs實現查詢天氣的小案例(跨域請求)

angularjs實現查詢天氣的小案例(跨域請求)

<!DOCTYPE html>
<html lang="en" ng-app="App">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
      
        .box {
        	position: relative;
        	width: 600px;
        	height: 400px;
        	margin: 0 auto;
        }
        .chaxun {
        	background-color: rgba(255,255,255,0.1);
        	position: absolute;
        	top:30px;
        	left: 50px;
        	/*float: left;*/
        }
        .bgimg {
        	width: 600px;
        }
	</style>

</head>
<body ng-app="App">
	
	<div ng-controller="WeatherController" class="box" >
	<img src="images/n-bg1.jpg" class="bgimg">
	<div class="chaxun">
		 <input type="text" ng-model="text">
	    <button ng-click="cha()">查詢當前位置天氣</button>
		<table>
			<!-- 檢視 -->
			<p>當前時間是:{{time|date:'yyyy-MM-dd hh:mm:ss'}}
</p> <tr ng-repeat="item in weatherData"> <!-- <p>你的位置:{{currentCity}}</p> --> <td>{{item.date}}</td> <td><img ng-src="{{item.dayPictureUrl}}" alt=""></td> <td><img ng-src="{{item.nightPictureUrl}}" alt=""></td> <td>{{item.temperature}}</td> <td>{{item.weather}}</td> <td>{{item.wind}}</td> </tr> </table> </div> </div> <script src="js/angular.min.js"></script> <script> var App = angular.module('App', []); // 定義控制器並宣告依賴 App.controller('WeatherController', ['$scope', '$http', '$interval', function($scope, $http, $interval)
{ // 頁面顯示當前時間 $interval(function(){ $scope.time = new Date(); },1000); // 查詢各個城市的天氣 $scope.text = '吉林';//初始化輸入框的引數 $scope.cha = function(){ $http({ method: 'jsonp', // 支援jsonp, url: 'http://api.map.baidu.com/telematics/v3/weather?callback=JSON_CALLBACK', params: { // 請求的引數 location: $scope.text, output: 'json', ak: '0A5bc3c4fb543c8f9bc54b77bc155724' } }).success(function (data)
{ // 請求回的資料放到模型上 $scope.currentCity = data.results[0].currentCity; $scope.weatherData = data.results[0].weather_data; }); } }]); </script> </body> </html>