前言:
经过2天的学习,基本上掌握了javascript和json和ajax,下面我将搭建一个很不规范的REST框架,为web2.0开放api做准备。
正文:
1 下载:json.js,Newtonsoft.Json.dll
2 自己写一个ajax.js
function
CreateAjaxRequest() {
var
req;
if
(window.XMLHttpRequest) {
req
=
new
XMLHttpRequest();
}
else
if
(window.ActiveXObject) {
req
=
new
ActiveXObject(
"
Microsoft.XMLHTTP
"
);
}
return
req;
}
3.添加一个IHttpHandler,作为REST的数据源,他的输出符合Json规范,大概意思很简单,从传入的参数里面获取变量,然后查数据库取得datatable,最后经过json的序列化返回response。
Code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Pixysoft.Framework.Noebe;
using System.Collections.Generic;
/// <summary>
/// RESThandler 的摘要说明
/// </summary>
[Pixysoft.Framework.Security.Entity.SkipPage]
public class RESThandler : IHttpHandler
{
private const int DefaultCountNumber = 6;
#region IHttpHandler 成员
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Clear();
context.Response.ClearContent();
string type = context.Request.QueryString["type"];
string count = context.Request.QueryString["count"];
if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(type.Trim()))
{
context.Response.Write("");
return;
}
int countNum;
if (!int.TryParse(count, out countNum))
{
countNum = DefaultCountNumber;//default value
}
if (countNum < 0 || countNum > 12)
countNum = DefaultCountNumber;
switch (type)
{
case RestType.hotproduct:
{
INoebeCommand command = NoebeManager.Instance.NoebeCommand;
command.SQL = "SELECT TOP " + countNum + " WEB_ITEMINFO.ITEMCODE AS ITEMCODE,WEB_ITEMINFO.ITEMNAME AS ITEMNAME,WEB_ITEMINFO.PRICE AS PRICE,WEB_ITEMIMG.THUMBPICURL AS THUMBPICURL FROM WEB_ITEMINFO INNER JOIN WEB_ITEMIMG ON WEB_ITEMINFO.ITEMCODE = WEB_ITEMIMG.ITEMCODE ORDER BY WEB_ITEMINFO.CREATEDATE,WEB_ITEMINFO.MODIDATE";
DataTable table = command.ExecuteReader();
List<HotProduct> list = new List<HotProduct>();
foreach (DataRow row in table.Rows)
{
HotProduct pro = new HotProduct();
pro.Imgurl = GetImageUrl(row["THUMBPICURL"].ToString());
pro.Price = double.Parse(row["PRICE"].ToString()).ToString(".00");
pro.Productname = Pixysoft.StringCoder.StringTrim(row["ITEMNAME"].ToString(), 15);
pro.Url = "common/item.aspx?itemcode=" + row["ITEMCODE"].ToString();
list.Add(pro);
}
context.Response.Write(Pixysoft.Json.MyJson.Instance.Serialize(list));//我把Json.net封装了一下,实际上还是调用了他的javascript.serialize的方法
return;
break;
}
default:
{
context.Response.Write("");
return;
break;
}
}
}
#endregion
private string GetImageUrl(string url)
{
if (!url.StartsWith("http://"))
{
return HttpContext.Current.Server.MapPath(url);
}
return url;
}
}
[Serializable]
public class HotProduct
{
string imgurl;
string url;
string productname;
string price;
public string Imgurl
{
get { return imgurl; }
set { imgurl = value; }
}
public string Url
{
get { return url; }
set { url = value; }
}
public string Productname
{
get { return productname; }
set { productname = value; }
}
public string Price
{
get { return price; }
set { price = value; }
}
}
class RestType
{
public const string hotproduct = "hotproduct";
}
4.在web.config里面注册这个handler
<add verb="GET" path="REST.do" type="RESThandler,App_Code"/>
因为我的handler在web项目里面写的,所以type的dll引用了App_Code
5.写一个REST_product_preload.js,目的是动态导入需要使用的ajax.js/json.js,当然还有自己定义的css
//
写下一个mark,被ajax填充
this
.server
=
'
http://localhost:3652/Pixysoft.Web.CitiBox
'
;
document.write(
'
<span id="ajaxresponse"><p style="text-aligh:center;">Please wait</p></span>
'
);
var
usrdefaultcss
=
true
;
if
(
typeof
defaultcss
==
'
undefined
'
)
{
usrdefaultcss
=
true
;
}
else
{
usrdefaultcss
=
defaultcss;
}
if
(usrdefaultcss)
LoadJsCssFile(
this
.server
+
'
/App_Themes/REST/REST_product.css
'
,
'
css
'
);
LoadJsCssFile(
this
.server
+
'
/js/ajax/ajax.js
'
,
'
js
'
);
LoadJsCssFile(
this
.server
+
'
/js/json/json.js
'
,
'
js
'
);
//
动态加载css
function
OnloadCss(href)
{
document.createStyleSheet(href);
}
//
http://homepage.yesky.com/45/7728545.shtml
function
LoadJsCssFile(filename, filetype)
{
if
(filetype
==
"
js
"
)
{
//
判断文件类型
var
fileref
=
document.createElement(
'
script
'
)
//
创建标签
fileref.setAttribute(
"
type
"
,
"
text/javascript
"
)
//
定义属性type的值为text/javascript
fileref.setAttribute(
"
src
"
, filename)
//
文件的地址
}
else
if
(filetype
==
"
css
"
)
{
//
判断文件类型
var
fileref
=
document.createElement(
"
link
"
)
fileref.setAttribute(
"
rel
"
,
"
stylesheet
"
)
fileref.setAttribute(
"
type
"
,
"
text/css
"
)
fileref.setAttribute(
"
href
"
, filename)
}
if
(
typeof
fileref
!=
"
undefined
"
)
document.getElementsByTagName(
"
head
"
)[
0
].appendChild(fileref)
}
6.写一个REST_product.js,这个就是调用ajax读取handler的json数据,并且显示到页面。(我就被一个ajax问题搞了很久,终于发现通过写<span>,然后替换里面的span.htmltext就可以实现动态加载数据)
//
获得数据
req
=
CreateAjaxRequest();
try
{
req.onreadystatechange
=
handleStateChange;
req.open(
"
GET
"
,
'
REST.do?type=hotproduct&count=
'
+
productnumber,
true
);
req.send(
null
);
}
catch
(exception)
{
alert(
""
);
}
//
取得数据,并且处理
function
handleStateChange()
{
if
(req.readyState
==
4
)
{
if
(req.status
==
200
||
req.status
==
0
)
{
//
取得返回字符串
var
resp
=
req.responseText;
//
构造返回JSON对象的方法
var
json
=
resp.parseJSON();
//
构造返回结果
//
显示返回结果
document.getElementById(
"
ajaxresponse
"
).innerHTML
=
GetProductResponse(json);
}
}
}
function
GetProductResponse(json)
{
var
retvalue
=
''
;
retvalue
+=
'
<div class="lstContent_product">
'
;
retvalue
+=
'
<ul>
'
;
for
(i
=
0
;i
<
json.length;i
++
)
{
retvalue
+=
'
<li>
'
;
retvalue
+=
'
<p class="product_img">
'
;
retvalue
+=
'
<a href="
'
+
json[i].Url
+
'
" title="
'
+
json[i].Productname
+
'
" target="_blank" >
'
;
retvalue
+=
'
<img src=
'
+
json[i].Imgurl
+
'
alt="" />
'
;
retvalue
+=
'
</a>
'
;
retvalue
+=
'
</p>
'
;
retvalue
+=
'
<p class="product_name">
'
;
retvalue
+=
'
<a href="
'
+
json[i].Url
+
'
" title="
'
+
json[i].Productname
+
'
" target="_blank" >
'
+
json[i].Productname
+
'
</a>
'
;
retvalue
+=
'
</p>
'
;
retvalue
+=
'
<p class="product_retailprice">
'
;
retvalue
+=
'
零售价 ¥
'
+
json[i].Price
+
''
;
retvalue
+=
'
</p>
'
;
retvalue
+=
'
<p class="product_lotprice">
'
;
retvalue
+=
'
批发价: [登录问价]</p>
'
;
retvalue
+=
'
</li>
'
;
}
retvalue
+=
'
</ul>
'
;
retvalue
+=
'
</div>
'
;
return
retvalue;
}
7. 新建一个html页面,输入一下代码:
<
html
>
<
head
>
</
head
>
<
body
>
My Hot Product!
<
script
language
="javascript"
>
productnumber
=
4
;defaultcss
=
true
;
</
script
>
<
script
language
="javascript"
type
="text/javascript"
src
="js/REST/REST_product_preload.js"
>
</
script
>
<
script
language
="javascript"
type
="text/javascript"
src
="js/REST/REST_product.js"
>
</
script
>
</
body
>
</
html
>
后记:
本REST框架需要ajax、json背景知识,引用了json.js,json.net类库
本REST例子无法正常运行,紧紧作为一个思路。如果需要正常运行,还需要我们公司自己的框架。当然经过合理的修改是可以正常运行的。