
需求:在网页上添加个天气预报。
以前总是在需要执行js的地方,直接写function(){}。在需要同样功能的地方直接copy,或者稍微修改。
然后在网上看看有没有好点的方法,然后就看到js面向对象编程,看了一些代码,感觉真不错。这些代码在以前做项目时也有看到过。当时只要能实现就忙于交差。没有多点的留意。
于是,就想整理一下,以便以后提醒自己。
js文件:
AutoWeather.js
AutoWeather = function (config) {
this.renderTo = config.renderTo || $(document.body); /*content*/
this.render = typeof (this.renderTo) == "string" ? $("#" + this.renderTo) : $(this.renderTo); //渲染的控件
this.city = config.city; //属性
this.init(); //初始化
}; AutoWeather.prototype = {
init: function () {
var autoEntity = this;
this.autoDate = $("<span id='autow-date'></span>"); //创建控件
this.render.append(this.autoDate);
this.autoWeather = $("<span id='autow-weather'></span>");
this.render.append(this.autoWeather);
$.ajax({
type: 'post',
url: 'PostWeather.ashx', //部署时,要虚拟路径 从网站根目录开始
data: { city: autoEntity.city },
dataType: "text",
async: true, //true:异步 false:同步
success: function (data) {
var json = $.parseJSON(data);
alert(data);
$("#autow-date").text(json[0].formateDate);
var s = json[0].weather + getNumberFromStr(json[0].temp1) + "-" + json[0].temp2;
$("#autow-weather").text(s);
}
});
} }; function getNumberFromStr(value) {
var reg = /\d+/;
var res = value.match(reg);
return res;
}
Handler文件:
//数据来自 中国气象网站的天气信息 public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string str = "";
string city = context.Request["city"];//城市编号
WebClient _client = new WebClient();
try
{
Stream objStream = _client.OpenRead("http://www.weather.com.cn/data/cityinfo/"+city+".html");
StreamReader _read = new System.IO.StreamReader(objStream, System.Text.Encoding.UTF8);
string readStr = _read.ReadToEnd();
int startIndex = readStr.IndexOf(':')+;
str = "[{\"formateDate\":\""+GetCurrentDate()+"\","+readStr.Substring(startIndex, readStr.Length - startIndex-)+"]";
}
catch (Exception ex)
{ }
context.Response.Write(str);
} public string GetCurrentDate() {
string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
string preStr = DateTime.Now.ToString("yyyy年MM月dd日");
string endStr = Day[Convert.ToInt32(DateTime.Now.DayOfWeek.ToString("d"))].ToString();
return preStr + " " + endStr;
}
Html文件:
<head runat="server">
<title></title>
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="AutoWeather.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var _weather = new AutoWeather({
renderTo: "info",
city: "101190201" //无锡的编号
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<!--显示天气的地方-->
<div id="info">
</div>
</form>
</body>
</html>
写下来,以后方便使用,和大家分享一下。