gpt4 book ai didi

jquery - 格式化 Jquery AJAX post 以将数据发送到 WCF 服务

转载 作者:行者123 更新时间:2023-12-01 07:28:47 50 4
gpt4 key购买 nike

在我的服务契约(Contract)中,我有:

[OperationContract(Name = "TreeViewData")]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
TreeData[] TreeViewData(string RagId);

Tree 数据类很简单

public interface ITreeDataV1
{
string Id { get; set; }
string ParentId { get; set; }
string Text { get; set; }
string Value { get; set; }
}

[DataContract(Name = "TreeData",
Namespace = "http://xxx.com/2011/10/14/TreeDataV1")]
public class TreeData : ITreeDataV1
{
[DataMember(Name = "Id")]
public string Id { get; set; }

[DataMember(Name = "ParentId")]
public string ParentId { get; set; }

[DataMember(Name = "Text")]
public string Text { get; set; }

[DataMember(Name = "Value")]
public string Value { get; set; }
}

在我的服务逻辑本身中,我有:

public TreeData[] TreeViewData(string RagId)
{
// some code and return some array of TreeData
}

我的问题是当我创建 jquery $.ajax 请求时:

$.ajax(
{
type: "POST",
url: "http://xxx/Retriever.svc/UI/TreeViewData",
data: {"RagId":"121"},
dataType: "json",
success: function()
{
alert('pop the champagne');
}
}
);

我收到以下异常 -

The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding.

我几乎可以肯定错误在于我格式化请求数据位的方式。

有什么指点吗?

最佳答案

整个数据对象需要字符串化。实现此目的的一个简单方法是使用 JSON2 库中的 JSON.Stringify 方法。 (https://github.com/douglascrockford/JSON-js/blob/master/json2.js)

使用它会将其更改为:

<script src="JSON2.js" type="text/javascript"></script>
<script>
var myObj = {"RagId":"121"};
var jsondata = JSON.stringify(myObj);
$.ajax({
type: "POST",
url: "http://xxx/Retriever.svc/UI/TreeViewData",
data: jsondata,
dataType: "json",
success: function()
{
alert('pop the champagne');
}
});
</script>

手动执行此操作看起来像:

var data = '{"RagID":"121"}';

但是,这种方法不灵活,并且在尝试手动字符串化复杂/动态对象时会浪费时间。

关于jquery - 格式化 Jquery AJAX post 以将数据发送到 WCF 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7800629/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com