您的位置:首页 > Web前端 > JQuery

jQuery调用WCF返回JSON对象

2011-01-13 16:58 423 查看
第一步:自定义数据类型(最终此类型以JSON的格式返回到客户端供解析)

JsonResult.cs 文件代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Runtime.Serialization;

[DataContract]
public class JsonResult
{
public JsonResult(string name, string address, string phone)
{
_name = name ;
_address = address;
_phone = phone;
}

private string _name;

[DataMember]
public string Name
{
get { return _name; }
set { _name = value; }
}

private string _address;

[DataMember]
public string Address
{
get { return _address; }
set { _address = value; }
}

private string _phone;

[DataMember]
public string Phone
{
get { return _phone; }
set { _phone = value; }
}
}

第二步:构建wcf服务

Service.svc 文件代码:

<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>

IService.cs 文件代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
JsonResult GetJsonResult(string name, string address, string phone);
}

Service.cs 文件代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

public class Service : IService
{
public JsonResult GetJsonResult(string name, string address, string phone)
{
JsonResult result = new JsonResult(name, address, phone);
return result;
}
}

第三步:客户端调用wcf服务,并读取自定义数据类型(在客户端以JSON格式返回)

<script type="text/javascript" language="javascript">
function Call() {
$("#divMessagePanel").html("");
var formativeData = '{"name":"张三","address":"李四","phone":"王五"}';
$.ajax({
type: "post",
url: "../Service.svc/ajaxEndpoint/GetJsonResult",
contentType: "application/json;charset=utf-8",
data: formativeData,
success: function(data) {
alert(data);
var a = eval_r('(' + data + ')');
alert(a.GetJsonResultResult.Name);
$('#divMessagePanel').html("ok");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$("#divMessagePanel").html("error");
},
cache: false
});
}  
</script>

web.config中wcf的配置部分:

<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="jsonWcfBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="Service">
<!--注意此处的endpoint配置,address和contract两个属性,在客户端Js调用时会用的上-->
<endpoint address="ajaxEndpoint" behaviorConfiguration="jsonWcfBehavior" binding="webHttpBinding" contract="IService">
</endpoint>
</service>
</services>
</system.serviceModel>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: