【发布时间】:2019-12-07 03:36:46
【问题描述】:
我一直在关注有关设置启用 AJAX 的 WCF 服务并使用客户端访问它们的 Microsoft 教程。但是,尽管完全按照教程进行操作,但结果不会按预期显示。
我遵循了以下tutorial 的每一步。如果您想追溯我的工作,这可能很有用。我在 Visual Studio 2019 中工作,下面我粘贴了 WCF 服务和 Web 表单的代码。
//WCF service file defining the operation
namespace SandwichServices
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CostService
{
[OperationContract]
public double CostOfSandwiches(int quantity)
{
return 1.25 * quantity;
}
}
}
//.aspx file for the web form
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SandwichServices.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function Calculate() {
CostService.CostOfSandwiches(3, onSuccess);
}
function onSuccess(result) {
var myres = $get("additionResult");
myres.innerHTML = result;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/CostService.svc" />
</Services>
</asp:ScriptManager>
<input type="button" value="Price of 3 sandwiches" onclick="Calculate()" />
<br />
<span id="additionResult">
<br />
</span>
</form>
</body>
</html>
调试时页面正常生成按钮,但是点击按钮应该会显示3.75的结果。相反,不显示任何结果。查看页面源代码并检查控制台会在单击按钮时显示以下错误:“SCRIPT5009:'CostService' 未定义”。对于解决此问题的任何帮助将不胜感激。
【问题讨论】:
-
试试这个:document.getElementById("additionResult");而不是 $get("additionResult");
-
我继续试了一下,调试时没有任何变化。
-
检查您的浏览器调试器。看看你的javascript是否有错误。
-
是的,正如@BlueEyedBehemoth 所建议的那样,找出答案的最佳方法是调试您的代码。试试这个教程来帮助你:developers.google.com/web/tools/chrome-devtools/javascript
-
看起来问题出在Calculate函数上——如前所述,所涉及的错误是“未定义CostService”。不幸的是,我似乎找不到任何方法来解决这个问题。