【问题标题】:Couchapp: how to store a document?Couchapp:如何存储文件?
【发布时间】:2011-02-13 09:22:41
【问题描述】:

在完成couchapp tutorial 之后,必须完成最后一步:保存创建的披萨。

为此,我创建了一个 JS 函数“saveToppings”,它被执行(如 firebug 控制台所示)但在保存我的 JSON 文档时失败:

无法保存文档:文档必须是 JSON 对象。

所以我明白,我的文档不是 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"}]}

【问题讨论】:

    标签: javascript couchdb couchapp


    【解决方案1】:

    所以,刚刚想通了。

    我扩展了我的调试以从我的“toppings”对象中获取对象类型

    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!");
        }
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-06
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      • 2018-03-13
      相关资源
      最近更新 更多