jquery或者JavaScript调用WCF服务的方法

时间:2022-11-08 17:26:51
/******************************************************************

* Copyright (C): 一心堂集团

* CLR版本: 4.0.30319.18063

* 命名空间名称: WcfService1

* 文件名: IJoonService

* GUID1: b7bd3ab3-3668-4727-9416-f9845da207e1
创建人:尹明能 * 创建时间: 2014-9-24 13:13:09 ******************************************************************/ using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web; namespace WcfService1
{
//一定要取个名字,不然客户端访问不到
[ServiceContract(Namespace = "ymn", Name = "J")]
public interface IJoonService
{
//暴漏方法,并且返回json格式数据
[OperationContract]
JsonResult HelloWorld(); [OperationContract]
string HelloWorld2(); [OperationContract]
List<JsonResult> HelloWorld3(); } }

第一步,首先定义契约,创建一个接口

第二步实现接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text; namespace WcfService1
{ [AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class JsonWCF:IJoonService
{
// 要使用 HTTP GET,请添加 [WebGet] 特性。(默认 ResponseFormat 为 WebMessageFormat.Json)
// 要创建返回 XML 的操作,
// 请添加 [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// 并在操作正文中包括以下行:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; // 在此处添加更多操作并使用 [OperationContract] 标记它们 [WebInvoke(ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public JsonResult HelloWorld()
{ JsonResult jr = new JsonResult();
jr.Address = "tt";
jr.Name = "rrr";
jr.Phone = ""; // List<Admin> list = me.Admin.ToList();
return jr; }
public string HelloWorld2()
{
return "啊啊";
} public List<JsonResult> HelloWorld3()
{
List<JsonResult> list = new List<JsonResult>();
JsonResult jr = new JsonResult();
jr.Address = "tt";
jr.Name = "rrr";
jr.Phone = "";
JsonResult j = new JsonResult();
j.Address = "yy";
j.Name = "uu";
j.Phone = ""; list.Add(jr);
list.Add(j);
return list;
}
}
}

第三步另一个项目调用wcf服务,并解析json对象

 <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
<script src="<%= Url.Content("~/Scripts/jquery-1.4..js") %>"
type="text/javascript"></script> </head>
<body> <form id="form1" runat="server">
<div> <br />
<br />
<input id="btnQueryDictionary" type="button" value="测试" onclick="btnQuery();" />
<br />
<br />
消息: <p id="lblMsg"></p>
</div> <script type="text/javascript">
function btnQuery() { //非ajax请求
// var wcfProxy = new ymn.J();
// wcfProxy.HelloWorld(OnSucceededCallback, OnFailedCallback); //ajax 请求
$("#lblMsg").html(""); $.ajax({
type: "post", url: "http://localhost:2813/JsonWCF.svc/HelloWorld3",
contentType: "application/json;charset=utf-8",
data: "", //没有数据
success: function (data) {
$.each(data.d, function (i, item) {
$("#lblMsg").append(item.Address+"</br>");
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#lblMsg").html("error");
},
cache: false
}); }
function OnSucceededCallback(msg) {
//转换成json对象
var a = eval(msg);
$("#lblMsg").html(a.Address); // $.each(a, function (i, item) {
// $("#lblMsg").append(
// item.Address+"<br/>"
//
// );
// });
//
} function OnFailedCallback(error, userContext, methodName) {
alert("异常信息:" + error.get_message() + "\n" +
"异常类型:" + error.get_exceptionType() + "\n" +
"堆栈信息:" + error.get_stackTrace());
}
</script>     <asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="http://localhost:2813/JsonWCF.svc" />
</Services>
</asp:ScriptManager>
</form> </body>
</html>
--22后记知道那个“d”是干嘛滴了,不过一直没有更新,为了以后复习,备注在此        [OperationContract( Name = "DoWork4" )]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/DoWork4" )]
[return: MessageParameter( Name = "e" )]
public Person DoWork4( [MessageParameter( Name = "e" )] Person e ) {
// 在此处添加操作实现
return new Person() { Age = , Name = "远始天尊" };
}加重的两行,[return: MessageParameter( Name = "e" )]这一行影响返回JSON对象时的名称,就是传说中的"d",此时被声明为"e"了后一行 public Person DoWork4( [MessageParameter( Name = "e" )] Person e ) {这个影响的是方法接收JSON对象的参数名称,也被改为"e"了,呵呵