-1

我正在向我的服务器发布以下帖子,

$.ajax({
    url: url,
    data: JSON.stringify({ SecretKey: e.Code, CommentId: e.Id, Direction: direction, VoteType:1}),
    type: "POST",
    contentType: "application/json;charset=utf-8",
});

当请求发布时,它如下所示:

{"Direction":{"Id":1,"Code":"1234-5678-9012","Description":"This is 1 comment."},"VoteType":"1"}

为什么要Direction包装元素?通知VoteType不受影响?VoteType和其余变量之间的唯一区别是它VoteType是一个字面值——不引用一个对象。

完整模型,以防万一:

var model = {
    Id: ko.observable(0),
    Code: ko.observable(""),
    Description: ko.observable(""),
    Comments: ko.observableArray(),
    vote: function (e, direction) {
    $.ajax({
        url: url,
        data: { SecretKey: e.Code, CommentId: e.Id, Direction: direction, VoteType:1},
        type: "POST",
        contentType: "application/json;charset=utf-8",
    });
    },
    secretVote: function (e, direction) {
        $.ajax({
            url: url,
            data: { SecretKey: e.Code, Direction: direction, VoteType:0},
            type: "POST",
            contentType: "application/json;charset=utf-8",
        });
    },
    comment: sendComment
}
4

2 回答 2

1

当您调用JSON.stringify时,它将尝试序列化所有内容。description(由 key 标识Description)指向具有内部属性的复杂对象,因此JSON.stringify会将其序列化为 JSON。VoteType是一个键,因此将被序列化为 just VoteType

此外,您没有看到的原因SecretKeyCommentId它们undefined不会被JSON.stringify.

总而言之,这与键的有关,而不是键本身。在第一种情况下,Direction指的是一个复杂的对象,而在第二种情况下,VoteType指的是一个整数。

另一方面,您无需使用JSON.stringify;序列化数据。jQuery 会为你做到这一点。

于 2013-07-12T16:57:52.463 回答
0

这个:

JSON.stringify({ SecretKey: e.Code, CommentId: e.Id, Direction: direction, VoteType:1})

可以产出:

{"Direction":{"Id":1,"Code":"1234-5678-9012","Description":"这是 1 条评论。"},"VoteType":"1"}

如果您的e.Codee.Id未定义(然后删除SecretKeyCommentId字段)并且direction对象是:

{"Id":1,"Code":"1234-5678-9012","Description":"这是 1 条评论。"}`

于 2013-07-12T16:57:22.570 回答