【问题标题】:$.post(...) not recognizing JSON body$.post(...) 无法识别 JSON 正文
【发布时间】:2014-09-30 20:53:27
【问题描述】:

我正在尝试像这样向服务器发出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.JSobservableArray(),body设置如上。

服务器端,这是处理请求的代码:

[HttpPost]
public IQueryable<Measurement> GetMeasurements(MeasurementQuery queryOptions)
{
    ...
    if (queryOptions != null) {
        if (queryOptions.PatientAgeFilter.CompareOperator != CompareOperator.Any) {
            ...
        }
    }
}

我在if (queryOptions != null) 上设置了一个断点,并且queryOptions 不为空。但是queryOptions 的内容保持默认,即使我指定了body 中的字段(CompareOperator 应该等于 3,但它保持为 0 - 等于 CompareOperator.Any),所以POST 的主体请求未正确解析。

有人能帮我看看为什么会这样吗?非常感谢!

【问题讨论】:

  • self.results() 被视为method 调用
  • 也许您只需要对结果进行字符串化 - JSON.stringify(self.results())
  • @hindmost 这不是问题,我之前在其他请求中使用过,没有任何错误或其他任何问题。
  • @BobMac 结果如他们所愿,只是不是我预期的结果。

标签: javascript jquery asp.net-mvc json knockout.js


【解决方案1】:

您的post 方法在两个方面不正确:
1.如 cmets 中所述,您应该使用 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() 的默认内容类型。所以,我的下一个猜测是问题出在您的服务器模型上。确保 CompareOperatorMoreThanValLessThanVal 实际上是属性,而不是字段(以及您想要绑定的所有子字段)。 WEB API 不绑定字段。

【讨论】:

  • 问题不是回调函数,而是传递body。如果我在请求到达断点时查看body的内容,则值没有正确填写。
  • 查看我对问题的回答 - 正如我所料,问题是由请求正文引起的。
【解决方案2】:

问题是 - 正如我所想 - 请求正文没有正确到达服务器。我改变了这个

$.post(url, body, self.results, "json");

到下面

$.ajax({
    url:url,
    type:"POST",
    data:JSON.stringify(body), //necessary for the data to be parsed properly
    contentType:"application/json; charset=utf-8", //important!
    dataType:"json",
    success: function(results){
        self.results(results);
    }
});

现在它可以正常工作了。

我使用 this SO question 作为答案。

【讨论】:

  • 很高兴有帮助。虽然很奇怪,但我更新的答案没有奏效 - 我已经在我的机器上检查过,效果很好。
  • 我知道,我希望它也能工作。无论如何,我很高兴我解决了这个问题,为这个问题寻找了一天多。
猜你喜欢
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多