昨天,在博客园无意中看到一篇关于以Json格式调用Web Service的文章。
于是手痒,便琢磨着自己也写一个例子试一试。
最终,经过一些尝试。算是弄懂了其中的一些需要注意的地方。
首先,需要加上添加System.Web.Extension.dll引用。然后添加这么一句。
using System.Web.Script.Serialization;
GoodsModel.cs
[Serializable]
public class Goods
{
#region 公共成员属性
string g_id;
public string G_id
{
get { return g_id; }
set { g_id = value; }
}
string g_name;
public string G_name
{
get { return g_name; }
set { g_name = value; }
}
string g_type;
public string G_type
{
get { return g_type; }
set { g_type = value; }
}
int g_single;
public int G_single
{
get { return g_single; }
set { g_single = value; }
}
#endregion
}
用于测试的WebService
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]//这个必须有~
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
//这个可以不加--> [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string HelloWorld()
{
List<Model.Goods> list = new List<Model.Goods>();
Model.Goods goods = new Model.Goods();
goods.G_id = "1";
goods.G_name = "Hello World";
goods.G_single = 1;
goods.G_type = "test";
list.Add(goods);
list.Add(goods);
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(list);
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
function test(){
$.ajax({
type: "POST",
url: "http://localhost:2624/Service1.asmx/HelloWorld",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var test = eval( data.d );
$.each(test, function (i) {
alert(this.G_id);
})
},
error: function (message) { alert(message.responseText); }
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" οnclick="test()" />
</div>
</form>
</body>
</html>
下面是需要注意的一些地方:
- Service类,需要加上这么一个特性。[System.Web.Script.Services.ScriptService],允许前台进行调用。
- eval(data.d),eval()对data.d进行解析。
- .Net 3.5 不能直接用eval(data)。这是因为,调用web service返回的json字符串全被放在了d里面。即
{"d":"{"G_id":"1","G_name":"Hello World","G_type":"test","G_single":1},{"G_id":"1","G_name":"Hello World","G_type":"test","G_single":1}"}
- contentType: "application/json; charset=utf-8",这个也是必须的。