我正在尝试做一些我认为很简单的事情。我需要创建一个可以通过 JQuery 发布到的 WCF 服务。我的 WCF 服务中有一个操作,定义如下:
[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?),但没有任何运气。我如何让这个基本交互发挥作用?
谢谢!
最佳答案
我认为你必须在请求中对你的 json 数据进行字符串化。更多信息here 。您可能还想解析传入的响应数据,因为它会被字符串化返回。可以找到适合该任务的通用库 here .
例如:data: '{ message: "message", Urgency: "1"}',
关于jquery - WCF - "Encountered unexpected character ' c'。”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2484377/