我正在尝试了解以下代码片段的工作原理。设计它的人不在身边向我解释它是如何工作的(以及他/她为什么不使用 ajax 调用)。我问过几个同事,他们似乎没有正确的解释让我理解 JavaScript 如何能够直接访问 webmethod。我希望我的示例足够好,至少可以得到合理的解释,因为我无法发布原始代码。
网络服务
namespace ClientName.Version.Services
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class ClassName : System.Web.Service.WebService
{
[WebMethod(EnableSession = true)]
public List<ReturnData> WebMethod(string param1)
{
.
.
.
}
}
}
Javascript调用
(function(){
var param = "Broken down calls";
.
.
.
ClientName.Version.Services.ClassName.WebMethod(
param, function(dataReturnedFromService){
if(dataReturnedFromService != null){
//process data and append to html
}
}
);
})();
编辑: 在@matt 将我指向正确的位置之后,如果有人关心的话,除了他的回复之外现在更多 http://msdn.microsoft.com/en-us/library/bb398998(v=vs.100).aspx
或谷歌
“向客户端脚本公开 Web 服务”了解更多信息。
最佳答案
大概是这样的:
http://msdn.microsoft.com/en-us/library/bb310823(v=vs.100).aspx
您正在客户端生成一个代理类,该代理类将 AJAX 调用隐藏在一个看起来与服务器端几乎相同的界面之后。
如果您查看浏览器控制台中的网络选项卡,您可能会看到实际的 AJAX 调用。
在 MSDN 上简单搜索 ScriptServiceAttribute应该为您指明了正确的方向:
To invoke a Web service method from ECMAScript (JavaScript), you must apply the ScriptServiceAttribute attribute to the related Web service class. When you apply ScriptServiceAttribute to a Web service class definition that contains one or more methods with WebMethodAttribute applied, the proxy generation script creates a proxy object that corresponds to the Web service class.
看看你的页面,你应该有一个看起来像这样的部分:
<asp:ScriptManager runat="server" ID="scriptManager">
<Services>
<asp:ServiceReference
path="~/WebServices/SimpleWebService.asmx" />
</Services>
</asp:ScriptManager>
这就是添加代理的地方。
关于JavaScript 使用程序集名称直接调用 C# web 服务方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26508298/