您的位置:首页 > Web前端 > HTML

ajax怎么请求webserver的某个方法返回string

2015-07-20 13:31 501 查看
做数据交互的时候,处理后台程序,有的时候会用到一般处理程序(ashx),而webserver和一般处理程序有同样的功效,并且可以跨平台调用

关于两者的一些区别:

ashx是轻量级的使用方便,部署快速。一个webservice可以实现多个方法。 而ashx文件里只能完成一个方法。就是如果你的页面用到了很多ajax事件的话,如果用asmx方式只用写一个webservice把他们包括在内就可以了,而如果用ashx的话会有多个ajax事件就要写多少个ashx文件。

方法实例:

后台接口

#region 商品详情信息
[WebMethod(Description = "商品详情信息")]
public void DetailComm(int id)
{
string sql = string.Format(@"select * from Commodity where Id={0} and Visible = 1 update Commodity set CommStock+=1 where Id={0}", id);
DataTable dt = DBHelper.Instance().GetDataTableBySql(sql);
if (dt.Rows.Count > 0)
{

List<object> list = new List<object>();
for (int i = 0; i < dt.Rows.Count; i++)
{
int commid = Convert.ToInt32(dt.Rows[i][0]);
string name = dt.Rows[i][1].ToString();
decimal price = Convert.ToDecimal(dt.Rows[i][8]);
string img = dt.Rows[i][3].ToString();
int commvolume = Convert.ToInt32(dt.Rows[i][9]);
int commStock = Convert.ToInt32(dt.Rows[i][11]);
DateTime AddTime = Convert.ToDateTime(dt.Rows[i][13]);
list.Add(new { Commid = commid, Name = name, Img = img,Price=price ,Commvolume = commvolume, CommStock = commStock,AddTime=AddTime, state = 1 });
}
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(list));
}
else
{
string JsonStr = JsonConvert.SerializeObject(new { state = 0 });
HttpContext.Current.Response.Write(JsonStr);
}
}
#endregion


下面就详细说明一下它的定义以及调用:

1.引用

首先新建项目目录如下(记得调用JQ插件),添加webserver服务并引用服务,引用服务之前得启动(就是运行一遍asmx).

2.写将要调用的方法

由于是使用js里面的ajax调用服务并且需要返回JSON格式的字符串,所以需要添加[ScriptService]标记

方法“HelloWorld()”,返回string类型的字符串,序列化字符串。
这样后台的服务程序就部署完毕。

3.使用js调用webserver服务

每一个属性都有具体的作用(初学者不建议缩减代码,不知道属性作用可以百度去找),这样程序就可以正常访问了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息