【发布时间】:2012-04-08 21:17:18
【问题描述】:
我正在尝试从 JavaScript 调用 WebMethod。到目前为止,我有:
EMSWebService.asmx:
namespace EMSApplication.Web.WebServices
{
/// <summary>
/// Holds the Webservice methods of EMSApplication
</summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class EMSWebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
在 aspx 页面中我添加了以下内容:
<asp:ScriptManager ID="ScriptManager" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/EMSWebService.asmx" />
</Services>
</asp:ScriptManager>
<input onclick="callWebMethod();" id="btn" type="button" value="Click Me" />
JavaScript 是:
<script type="text/javascript">
function callWebMethod() {
EMSApplication.Web.WebServices.EMSWebService.HelloWorld(OnComplete, OnError);
}
function OnComplete(result) {
alert(result);
}
function OnError(result) {
alert(result.get_message());
}
</script>
但是方法没有执行。我收到以下 JavaScript 错误:
EMSApplication 未定义。
我有什么遗漏吗?我需要做一些其他的配置吗?
项目结构如下图所示:
JavaScript 和组件在 Login.aspx 中。
[WebService(Namespace = "http://tempuri.org/")]
的网址有什么意义
编辑:
我也尝试过使用 jQuery 并将 aspx 页面修改为:
$(document).ready(function () {
$("#btn").click(function () {
$.ajax({
type: "POST",
url: "../WebServices/EMSWebService.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (msg) {
alert(msg.d);
}
});
return true;
});
});
我在WebMethod 中写了System.Diagnostics.Debug.WriteLine("Hello World");,它正在执行,即它正在Visual Studio 的输出窗口中打印“Hello World”,但我没有收到任何警报消息。
【问题讨论】:
-
在客户端设置断点,例如在 Google Chrome 优秀的开发人员工具中查看 ajax 调用之前/之后发生的情况。
-
你能验证一下scripthandlerfactory是在web.config中定义的吗?
-
不,我没有在 web.config 中定义任何 scripthandlerfactory。我该怎么办?
-
阅读此处msdn.microsoft.com/en-us/library/bb398998.aspx 此页面介绍了从脚本调用 Web 服务所需的操作。
-
@JeremyHoward 你能发表你的答案吗?这样我才能接受。在
<system.web/>的<httpHandlers/>中使用<add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" validate="false"/>后解决。非常感谢。
标签: c# javascript exception-handling asmx