AjaxjQuery版

趙 北辰發表於2020-12-11
<head>
		<meta charset="utf-8">
		<title>實時天氣</title>
		<script src="jquery-3.5.1.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<select name="citys">
			<option value="101110101">西安</option>
			<option value="101100101">太原</option>
			<option value="101180101">鄭州</option>
			<option value="101270101">成都</option>
			<option value="101160101">蘭州</option>
			<option value="101200101">武漢</option>
			<option value="101040100">重慶</option>
			<option value="101170101">銀川</option>
		</select>
		<div id="tianqidiv"></div>
		<script>
			//var $cityidObj =  $("#citys");
			var $cityidObj =  $("select[name='citys']");			
			var cityid =$cityidObj.val();
			var cityname = $cityidObj.children().first().text();
			//var xiAn = cityname;
			window.onload = function(){
				getTianqi()
			}
			$cityidObj.on("change",function(){
					getTianqi($(this).val());
			});
			function getTianqi(csid){
				if(csid){
					cityid = csid;
				}
				$cityidObj.children().each(function(index,option){
					if(cityid == $(option).val()){
						cityname = $(option).text();
					}
				});
				var tiqiUrl = "https://devapi.qweather.com/v7/weather/now?"+
				"location="+cityid+"&key=????????????????";
				$("#tianqidiv").load(tiqiUrl,function(responseTXT,statusTXT,xhr){
					if(statusTXT == "success"){
						tiqiObj = JSON.parse(responseTXT);
						$(this).html(cityname+"實時天氣</br>"+"天氣:"+tiqiObj.now.text+"</br>溫度:"+tiqiObj.now.temp);
					}
					if(statusTXT == "error"){
						$(this).html("出錯編碼:"+xhr.status+"</br>出錯資訊"+statusTXT);
					}
				})
			}
				
		</script>
	</body>

相關文章