我正在尝试向服务器发出 POST
请求,如下所示:
var body = {
PatientAgeFilter: {
CompareOperator: parseInt(self.patientAge()),
MoreThanVal: {
AgeSpecifier: 0,
AgeValue: parseInt(self.patientAgeLow())
},
LessThanVal: {
AgeSpecifier: 0,
AgeValue: parseInt(self.patientAgeHigh())
}
}
};
$.post(url, body, self.results, "json").done(function () {
console.log("request done!");
console.log(self.results());
});
URL 设置正确,self.results
是一个 Knockout.JS observableArray()
,正文设置如上。
服务器端,这是处理请求的代码:
[HttpPost]
public IQueryable<Measurement> GetMeasurements(MeasurementQuery queryOptions)
{
...
if (queryOptions != null) {
if (queryOptions.PatientAgeFilter.CompareOperator != CompareOperator.Any) {
...
}
}
}
我在 if (queryOptions != null)
上设置了断点,并且 queryOptions 不为 null。但是,即使我在 body
中指定了字段,queryOptions
的内容仍保持默认状态(例如,CompareOperator
应等于 3,但它仍为 0 -等于 CompareOperator.Any
),因此 POST
请求的正文无法正确解析。
有人可以帮我解释一下为什么会发生这种情况吗?非常感谢!
最佳答案
您的post
方法有两种不正确的地方:
<删除>1。正如评论中已经指出的,您应该使用 JSON.stringify
获取您的数据。(请参阅下面的更新)
2. 第三个参数(如果存在)必须是 success callback .
所以,这个变体应该可以工作:
...
$.post(url, JSON.stringify(body), function(results) {
self.results(results);
}, "json");
更新 1:
问题不在 JSON.stringify
事实上,因为 WEB Api 默认支持 application/x-www-form-urlencoded
这是 $post()
的默认内容类型。所以,我的下一个猜测是问题出在你的服务器模型上。确保CompareOperator
, MoreThanVal
和LessThanVal
实际上是属性,而不是字段(以及您想要绑定(bind)的所有子项)。 WEB API 不绑定(bind)字段。
关于javascript - $.post(...) 无法识别 JSON 主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25185490/