积极答复者
Ajax客户端访问Wcf服务,出错:未定义

问题
-
vs2013中右击网站项目/添加/新建项/Wcf服务, 然后命名"abcService.svc"
IabcService.cs文件代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IabcService”。
[ServiceContract]
public interface IabcService
{
[OperationContract]
string Hello(string yourName);
}
abcService.cs文件代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“abcService”。
public class abcService : IabcService
{
public string Hello(string yourName)
{
return string.Format("Hello {0}", yourName);
}
}
Default2.aspx页面如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/abcService.svc" />
</Services>
</asp:ScriptManager>
<input id="Button1" type="button" value="button" />
</div>
</form>
</body>
</html>
<script type="text/javascript">
var abcSer;
function pageLoad() {
abcSer = new abcService();
$addHandler($get("Button1"), "click", clickFun);
}
function clickFun() {
abcSer.Hello("计算机", sucFun);
}
function sucFun(r) {
alert(r);
}
</script>ctrl+F5后显示:
行:74
错误:"abcService"未定义
答案
全部回复
-
你好,
根据你的描述,我建议你可以使用下面的代码来调用WCF服务:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type = "text/javascript"> $("#search").live("click", function () { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: '<%=ResolveUrl("~/Services/Service.svc/GetCustomers") %>', data: '{"prefix": "' + $("#prefix").val() + '"}', processData: false, dataType: "json", success: function (response) { var customers = eval(response.d); var html = ""; $.each(customers, function () { html += "<span>Name: " + this.Name + " Id: " + this.Id + "</span><br />"; }); $("#results").html(html == "" ? "No results" : html); }, error: function (a, b, c) { alert(a.responseText); } }); }); </script>
更多详细信息,请参考下面的链接:
http://www.aspsnippets.com/Articles/Consuming-WCF-Rest-Service-using-jQuery-AJAX-in-ASPNet.aspx
http://www.cnblogs.com/ttltry-air/archive/2009/12/05/1617483.html
http://www.cnblogs.com/cokkiy/archive/2009/10/22/jsCallWCF.html