【问题标题】:Formatting a Jquery AJAX post to send data to WCF service格式化 Jquery AJAX 帖子以将数据发送到 WCF 服务
【发布时间】:2011-10-17 23:04:05
【问题描述】:

在我的服务合同中,我有:

[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');
    }
}
);

我得到以下异常 -

传入的消息具有意外的消息格式“原始”。这 该操作的预期消息格式为“Xml”、“Json”。这个可以 是因为没有配置 WebContentTypeMapper 绑定。

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

任何指针?

【问题讨论】:

    标签: jquery .net wcf json


    【解决方案1】:

    整个数据对象需要被字符串化。一个简单的方法是使用 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"}';
    

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

    【讨论】:

      【解决方案2】:

      您是否尝试在 JQuery ajax 请求中设置 contentType?

      contentType: "application/json; charset=utf-8"
      

      【讨论】:

        猜你喜欢
        • 2012-04-15
        • 2020-10-30
        • 2014-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多