我正在尝试使用C#和javascript自学AJAX / Web服务。而且我认为我有一个名称空间问题,从我做过的谷歌判断来看。
首先,我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace SimpleAJAX
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string GetServerResponse(string callerName)
{
if (callerName == string.Empty)
throw new Exception("Web Service Exception: invalid argument");
return string.Format("Service responded to {0} at {1}", callerName, DateTime.Now.ToString());
}
}
}
网络服务。
<head id="Head1" runat="server">
<title>Web Service call from client-side JavaScript</title>
<script language="javascript" type="text/javascript">
function SendRequest() {
MySampleService.GetServerResponse(form1.MyTextBox.value, OnComplete, OnError, OnTimeOut);
}
function OnComplete(arg)
{
alert(arg);
}
function OnTimeOut(arg)
{
alert("timeOut has occured");
}
function OnError(arg)
{
alert("error has occured: " + arg._message);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/MySampleService.asmx" />
</Services>
</asp:ScriptManager>
<div>
<input type="text" value="" id="MyTextBox" />
<input type="button" value="Send Request to the Web Service" id="RequestButton"
onclick="return SendRequest()" />
</div>
</form>
</body>
aspx页面。
取自(http://www.semenoff.dk/en/Code-Corner/ASP.Net.AJAX/WebService-From-JavaScript.aspx)
当我运行它时,我得到一个“'MySampleService'未定义”错误。我完全按照教程,但显然我仍然做错了。帮助不大?谢谢!
答案 0 :(得分:2)
您需要在调用中包含您的命名空间和服务的实际类名:
SimpleAJAX.WebService1.GetServerResponse(form1.MyTextBox.value, OnComplete, OnError, OnTimeOut);
要查看ASP.NET为ScriptReference生成的JavaScript代理的确切结构,请在浏览器中打开WebService1.asmx/jsdebug
。
答案 1 :(得分:1)
试试这个
function SendRequest() {
SimpleAJAX.WebService1.GetServerResponse(form1.MyTextBox.value, OnComplete, OnError, OnTimeOut);
}
答案 2 :(得分:1)
您没有任何名为“MySampleService”的课程。您的类名为WebService1,因此您应该使用
SimpleAJAX.WebService1.GetServerResponse(form1.MyTextBox.value, OnComplete, OnError, OnTimeOut);