使用json存储创建的2个var项

时间:2014-12-02 13:25:14

标签: javascript json

所以我有一个小问题。我需要使用JSON存储特定信息(描述和日期)。我当前的Javascript是:

    var main = function () {

    var dates = {};

    var addCommentFromInputBox = function () {
        var $newcomment

         if ($(".comment-input input").val() !== "") {
            $new_comment = $("<p>").text($(".comment-input input").val());
            if ($(".date-input input").val() !== "") {
                $new_date = $("<p>").text($(".date-input input").val());
            } else {
                $new_date = $("<p>").text("indetermined");
            }
            $new_date.hide();
            $new_comment.hide();
            $(".comments").append($new_comment);
            $(".date").append($new_date);
            $new_comment.fadeIn();
            $new_date.fadeIn();
            $(".comment-input input").val("");
            $(".date-input input").val("");
        } else {
            window.alert("Please fill in some text");
        }
    }; 

    $(".comment-input button").on("click", function (event) {
        addCommentFromInputBox();
    }); 

    $(".comment-input input").on("keypress", function (event) {
        if (event.keyCode == 13) {
            addCommentFromInputBox();
        }
    });

    $(".date-input button").on("click", function (event) {
        addCommentFromInputBox();
    }); 

    $(".date-input input").on("keypress", function (event) {
        if (event.keyCode == 13) {
            addCommentFromInputBox();
        }
    });

};
$(document).ready(main);  

现在我需要将创建的对象存储到服务器。我想知道最好的方法是什么。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

使用类似的东西:

var dates = [];

并初始化一个这样的日期对象:

date = {
    "date": "",
    "desc": ""
}

使用以下方法填写当前对象的值:

date.date = value;
date.description = desc;

并将其添加到原始数组中,如:

dates.push(date);

您可以将单个JSON发送到服务器:

$.post(url, date, function (response) {});

或者,这样整个阵列:

$.post(url, dates, function (response) {});

&#13;
&#13;
arrA = ["2014-01-01", "2014-02-14", "2014-05-01"];
arrB = ["New Year", "Valentine's Day", "May Day"];

var dates = [];

for (i = 0; i < 3; i++)
{
  date = {
    "date": "",
    "desc": ""
  }

  date.date = arrA[i];
  date.desc = arrB[i];

  dates.push(date);
}
console.log(dates);
&#13;
&#13;
&#13;