我的服务合同的方法如下:
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "FibonacciNumber/")]
long FibonacciNumber(long n);
public long FibonacciNumber(long n)
{
var a = 0;
var b = 0;
for(var i = 0; i <= n; i++)
{
if(i == n)
{
return a;
}
var c = a;
a = b;
b = b + c;
}
return 0;
}
但是,当我尝试使用jquery ajax调用调用上面的内容时,参数&#34; n&#34;当FibonacciNumber服务被击中时,它是0,任何想法可能是错的?我做了控制台记录&#34; $(&#39;#fibIndex&#39;)的价值.val()&#34;它在客户端显示正确的值:
$('#btnFib').on('click', function () {
fibIndex = $('#fibIndex').val();
$.ajax({
url: "http://localhost:61924/MyService.svc/FibonacciNumber/",
type: "POST",
dataType: "json",
data: Number(fibIndex),
}).done(function (data) {
$('#fibResult').html(data);
}).fail(function () {
console.log("error");
});
});
提前感谢您在这方面有所了解。
答案 0 :(得分:0)
我发现我的代码存在问题。问题是我缺少contentType而没有传递正确的数据。正确的例子如下:
$('#btnFib').on('click', function () {
var fibIndex = Number($('#fibIndex').val());
$.ajax({
url: "http://localhost:61924/MyService.svc/FibonacciNumber/",
type: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(fibIndex),
}).done(function (data) {
$('#fibResult').html(data);
}).fail(function (a) {
console.log(a);
});
});