实例——输入城市显示该城市的天气信息

这段代码展示了如何使用jQuery通过AJAX从远程服务器获取北京的天气信息,并将获取到的预报数据解析并显示在页面上。用户点击按钮后,会读取输入的城市名称(默认为北京),然后加载JSON数据,解析后的数据包括日期、最高温度、风力、最低温度、风向和天气类型等,这些信息会被添加到页面的div中。
摘要由CSDN通过智能技术生成

代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
	<title></title>
	<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
    	
   		document.addEventListener('plusready', function(){
   			//console.log("所有plus api都应该在此事件发生后调用,否则会出现plus is undefined。")
   			
   		});  
	
		/*----------Jquery事件--------------*/
		$(document).ready(function(){
			$("button").click(function(){
		/*-----------------------------------begin--------------------------------*/
		/*------说明:通过ajax获取远程服务器(url:http://wthrcdn.etouch.cn/weather_mini?city=)天气信息(json数据),解析获取的字条串,
		转化成为对象,获取forecast数组,调用addBox()函数---------*/
		
		var city=$("#city").val();
		$.ajax({
			type:"GET",
			url:"http://wthrcdn.etouch.cn/weather_mini?city=北京",
			dataType:"json",
			success:function(result){
		    addBox(result.data.forecast);
			}
		});
		/*-----------------------------------end--------------------------------*/		
		});
		});		
			
				
		function addBox(json_data) {
			
				$.each(json_data, function(index, obj) {
					
					$("#box").append("<div'>" +
						
							"<p>" + obj['date'] + "</p>" +
							
							
							"<p>" + obj['high'] + "</p>" +
							
							"<p>" + obj['fengli'] + "</p>" +
							
							"<p>" + obj['low'] + "</p>" +
							
							"<p>" + obj['fengxiang'] + "</p>" +
							
							"<p>" + obj['type'] + "</p>" +
							
							"</div>");
				});							
		}
    </script>
	
</head>
<body>
	<div>
		<h3>请输入城市:</h3>
		城市:<input type="text" id="city"/>
		<br>
		<button type="button">提交</button>
	</div>
	
	<br>
	
	<div id="box"></div>	
	
</body>
</html>

效果图:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值