-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(キーによって識別されるDescription) は、内部プロパティを持つ複雑なオブジェクトを指しているため、JSON.stringifyそれを JSON にシリアル化します。VoteTypeはキーであるため、単に としてシリアル化されますVoteType

SecretKeyまた、とが表示されない理由は、CommentIdによってundefinedシリアル化されないためJSON.stringifyです。

要約すると、これはキー自体よりもキーの値に関係があります。最初のケースでDirectionは複雑なオブジェクトを参照し、2 番目のケースで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.Codeande.Idが定義されていない場合( SecretKeyandCommentIdフィールドが削除されている場合)、およびdirectionobject が次の場合:

{"Id":1,"コード":"1234-5678-9012","説明":"これは 1 コメントです。"}`

于 2013-07-12T16:57:22.570 に答える