在MS Ajax中,JS与C#交互的一种方式就是调用WebService,该WebService可以ASMX的也可以是WCF的,不论哪种方式,系统都会自动为开发者生成代理的JS类。实现方法如下:
1. 建立一个网站,并在其中添加一个WCF服务(这里一定要选择Ajax-Enabled WCF Service),如下图所示:

2. IDE会自动为我们生成一个SVC文件,是对外的接口,以及该SVC对应的后台实现类,该类文件会被放在App_Code下,如下图所示:
3.修改该类的代码,如下所示: 
复制代码 代码如下:
 
[ServiceContract(Namespace = "TestAjax")] 
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
public class Service 
{ 
[OperationContract] 
public bool ValidateUser(string uid, string pwd) 
{ 
if (uid=="sa"&&pwd=="sa") 
{ 
return true; 
} 
return false; 
} 
} 
复制代码 代码如下:
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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> 
</head> 
<body> 
<form runat="server"> 
<div> 
<asp:ScriptManager runat="server"> 
<Services> 
<asp:ServiceReference Path="~/Service.svc"/> 
</Services> 
</asp:ScriptManager> 
</div> 
</form> 
</body> 
</html> 
复制代码 代码如下:
 
<script type="text/javascript"> 
function ValidateUser(uid, pwd) { 
TestAjax.Service.ValidateUser(uid,pwd,OnSucceed ,OnFailed ); 
} 
function OnSucceed(result) { 
if (result == true) { 
window.alert("通过验证"); 
} 
else { 
window.alert("验证失败!"); 
} 
} 
function OnFailed(result) { 
window.alert("操作失败:"+result ._message); 
} 
</script> 
复制代码 代码如下:
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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"> 
function ValidateUser(uid, pwd) { 
TestAjax.Service.ValidateUser(uid,pwd,OnSucceed ,OnFailed ); 
} 
function OnSucceed(result) { 
if (result == true) { 
window.alert("通过验证"); 
} 
else { 
window.alert("验证失败!"); 
} 
} 
function OnFailed(result) { 
window.alert("操作失败:"+result ._message); 
} 
function Button1_onclick() { 
var uid = $get("tbxUid").value; 
var pwd = $get("tbxPwd").value; 
ValidateUser(uid,pwd); 
} 
</script> 
</head> 
<body> 
<form runat="server"> 
<div> 
<asp:ScriptManager runat="server"> 
<Services> 
<asp:ServiceReference Path="~/Service.svc"/> 
</Services> 
</asp:ScriptManager> 
</div> 
用户名:<input type="text" /><br /> 
密码: <input type="text" /> 
<input type="button" value="验证" /> 
</form> 
</body> 
</html> 


新闻热点
疑难解答
图片精选