背景:
我创建了一个运行良好的 WCF 服务(.NET 3.5),需要使用 JavaScript 使用该服务,并且由于跨域限制(该服务与包含 javascript 的网页位于不同的服务器上) ,标准的肥皂帖不起作用。我更改了一些配置,根据 Microsoft 博客文章向该方法添加了 WebInvoke 属性,并让服务与 GET 一起工作,并通过使用 soapUI 测试确认该方法正在工作。我试图在 JSFiddle 上设置一个示例,但因为这是一个 Intranet 服务,我显然无法让它工作。
这是我的 SVC.cs 文件中的方法:(我在尝试解决这个问题时对配置文件进行了一些代码更改和更改)
// On the interface that defines the contract
[OperationContract]
[WebGet]
string Post(string questionid, string answervalue);
// In my actual service file code behine.
public string Post(string questionid, string answervalue)
{
Guid dataid = _dataProvider.Post(questionid, answervalue);
_dataProvider.Log(retval.ToString());
return dataid.ToString();
}
现在,如果我只输入 URL,我会得到一个表示该值的 GUID 的字符串表示形式。
http://localhost/WebPostSvc.svc/json/Post?questionid=207&answervalue=207009
returns: "<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">04bb6445-b1af-4214-8f8b-cf66bb15467f</string>"
这是我要开始工作的javascript:
<script type="text/javascript">
// string functions to allow formatted output
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
$(function()
{
$('.testpostbtn').click(function() {
$.jsonp({
url: "ttp://localhost/WebPostSvc.svc/json/Post?questionid=207&answervalue=207009",
callbackParameter: "callback",
"success" : function(data) {
alert(data);
},
"error" : function(d, msg) {
alert(
"Could not post the data\ncallback={0}\ncallbackParameter={1}\nurl={2}\n{3}\n"
.format(d.callback, d.callbackParameter, d.url, msg)
);
}
});
alert('request sent!');
});
});
</script>
$.jsonp 方法来自:
// jquery.jsonp 2.3.1 (c)2012 Julian Aubourg | MIT License
// https://github.com/jaubourg/jquery-jsonp
我所要做的就是从方法返回的错误,我将其发送到警报框:
Could not post the data
callback=_jqjsp
callbackParameter=callback
url=http://localhost/WebPostSvc.svc/json/Post?questionid=207&answervalue=207009
error
返回的唯一错误消息是“错误”,它不是很有帮助。
我确定我只是错误地使用了该方法,我需要知道:
我究竟做错了什么?