完成 couchapp tutoria 之后l,必须完成最后一步:保存创建的披萨。
为此,我创建了一个 JS 函数“saveToppings”,该函数被执行(如 Firebug 控制台所示)但无法保存我的 JSON 文档并显示消息:
The document could not be saved: Document must be a JSON object.
所以我明白,我的文档不是 JSON 文档,但我不知道如何正确执行此操作。
这是“saveToppings”函数的代码:
function(e){
var json_toppings = JSON.stringify($$(this).toppings);
var merged_toppings = "{ \"type\":\"topping\", \"contents\":" + json_toppings + "}";
$.log('json_toppings: '+ json_toppings.toString());
$.log('merged_toppings: '+ merged_toppings.toString());
$$(this).app.db.saveDoc(merged_toppings, {
success : function() {
alert("Doc saved successfully.");
}
});
}
...以及来自控制台的调试:
json_toppings: [{"top":"tomatoes"},{"top":"bacon"},{"top":"cheese"}]
merged_toppings: { "type":"topping", "contents":[{"top":"tomatoes"},{"top":"bacon"},{"top":"cheese"}]}
最佳答案
所以,刚刚想通了。
我扩展了我的调试以从我的“浇头”对象中获取对象类型
Object.prototype.toString.call(merged_toppings)
...它们是字符串。所以我现在使用 jquery 创建一个 JSON 对象:
var JSONtoppings = jQuery.parseJSON( merged_toppings );
...它正在运行。完整代码在这里:
function(e){
var json_toppings = JSON.stringify($$(this).toppings);
var merged_toppings = "{ \"type\":\"topping\", \"contents\":" + json_toppings + "}";
var JSONtoppings = jQuery.parseJSON( merged_toppings );
$.log('json_toppings: '+ json_toppings.toString());
$.log('json_toppings type: ' + Object.prototype.toString.call(json_toppings));
$.log('merged_toppings: '+ merged_toppings.toString());
$.log('merged_toppings type: ' + Object.prototype.toString.call(merged_toppings));
$.log('JSONtoppings: '+ JSONtoppings);
$.log('json_toppings type: ' + Object.prototype.toString.call(JSONtoppings));
$$(this).app.db.saveDoc(JSONtoppings, {
success : function() {
alert("Clicked the save buttoN!");
}
});
}
关于javascript - Couchapp:如何存储文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4983408/