2010-03-20 32 views
6

我正在尝试做一些我认为很简单的事情。我需要创建一个可以通过JQuery发布的WCF服务。我在被定义为如下我的WCF服务的操作:WCF - “遇到意外字符'c'。”

[OperationContract] 
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)] 
public string SendMessage(string message, int urgency) 
{ 
    try 
    { 
    // Do stuff 
    return "1"; // 1 represents success 
    } 
    catch (Exception) 
    { 
    return "0"; 
    } 
} 

然后我尝试通过JQuery从ASP.NET页面访问此操作。我的JQuery代码来访问此操作如下所示:

function sendMessage(message) { 
    $.ajax({ 
    url: "/resources/services/myService.svc/SendMessage", 
    type: "POST", 
    contentType: "application/json; charset=utf-8", 
    data: ({ message: message, urgency: '1' }), 
    dataType: "json", 
    success: function (data) { 
     alert("here!"); 
    }, 
    error: function (req, msg, obj) { 
     alert("error: " + req.responseText); 
    } 
    }); 
} 

当我执行此脚本时,错误处理程序被触发。其中,我收到一条错误消息:

“遇到意外字符'c'。”

此消息包含在一个长堆栈跟踪中。我的问题是,我做错了什么?我收到了其他的帖子,比如这个(How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?),没有任何运气。我如何获得这种基本的互动工作?

谢谢!

+1

我认为你传递的参数不正确。看看下面的页面:[在ASP.NET AJAX中使用jQuery时要避免的三个错误](http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery -with-aspnet-ajax /) – Giorgi 2010-03-20 19:29:58

+0

目前我无法访问该网站 - 它说了什么? – 2012-06-27 11:40:18

回答

3

我认为你必须在请求中将你的json数据串联起来。更多信息here。您可能还想分析传入的响应数据,因为它将作为回报进行字符串化。可以找到适合任务的公共图书馆here。例如:数据:'{message:'message',urgentncy:'1“}',

+0

我有这个相同的问题,事实证明你不应该将$ .ajax方法中的数据作为json对象传递,而是作为一个字符串。maets的答案是现货。 – 2012-09-05 12:46:11