【发布时间】:2016-03-03 06:45:56
【问题描述】:
我有一个 mvc 项目,我试图发布到我通过 Web 表单和 AJAX 调用创建的 WCF 服务。当它访问 WebService 时我收到一个错误,它说的是 GET。
AJAX 的重要部分如下所示:
var songRequest = {
Title: 'New Slang',
Artist: 'The Shins',
Genre: 'Indie',
Difficulty: 'Easy',
id: 11
};
$(document).ready(function () {
$("#createSong").on("click", "#saveSong", function () {
$.ajax({
url: 'http://localhost:17476/SongRESTService.svc/json/PostJson/',
dataType: 'jsonp',
contentType: 'application/json',
data: JSON.stringify(songRequest),
method: "POST"
}).done(function (response, b, c) {
console.log(response, b, c);
}).error(function (xhr) {
console.log(xhr);
alert("There was an error saving the song. Please try again.");
});
});
});
通常会从表单生成数据,但我只是为了测试目的对其进行了硬编码。
webservice 部分如下所示:
[OperationContract]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "json/PostJson/")]
String PostJson();
有什么想法吗?
【问题讨论】:
-
我们需要查看实际错误,进入 Chrome 中的网络选项卡并查看请求/响应。
-
您是否在服务端启用了
JSONP或CORS?您似乎没有给出错误消息。您似乎违反了此 AJAX 请求的同源策略。 -
DavidG,我添加了图片,但我认为它没有提供更多信息
-
达林,我不这么认为。我已经用谷歌搜索了很多,但还没有找到在服务端启用它的位置。
-
是的,它显示 HTTP 405,这意味着该服务不接受您正在使用的 HTTP 方法。
标签: c# jquery ajax web-services wcf