【问题标题】:jQuery : update the database with all of the data from the ajax-requestjQuery:使用来自 ajax-request 的所有数据更新数据库
【发布时间】:2013-08-29 11:59:05
【问题描述】:

我正在尝试更新数据库。

因为我正在这样做

来自js代码

var data = {
    "jobid": $('#jobid').val(),
    "names": $('#names').val(),
    "scripttype": $('#testscripts').val()
};
var msg="";
for(i = 1; i <=4; i++) { 
    data["Param" + i + "Key"] = $('#key' + i).val();
    data["Param" + i + "Value"] = $('#value' + i).val();
}
        $.ajax({
            type: 'post',
            url: "/save",
            dataType: "json",
            data: data                
        });

在 node.js 端

jobsCollection.update({
            _id: id
        }, {
            $set: {
                names: record.names,         
                script: record.scripttype,
                // i dont know what should i place in this part???  
               //   i have to set paramkey and paramValues       
            }
        },
                     {
             upsert: true 
             },
        function (err, result) {
            if (!err) return context.sendJson([], 404);
        });

在 record.names 和 record.scripttype 中获取正确的值。

I don't know how to set values got from the for loop for updating

request going

Request: /save
{ jobid: '',
  names: 'first',
  scripttype: 'fow',
  Param1Key: '1',
  Param1Value: 'oneeeeee',
  Param2Key: '2',
  Param2Value: 'twoooooooo'
  etc........
  ............
 }

【问题讨论】:

    标签: javascript jquery ajax mongodb


    【解决方案1】:

    由于属性名称是动态的,因此您需要使用 JavaScript 的 indexer-style 属性访问器,如下所示。

    基本上把这个过程倒过来。我不确定数据在您调用update 时的位置,因此在下面的示例中我将其称为sourceData

    // create an object with the well known-property names
    var set = {
        names : record.names,
        script : record.scripttype
    };
    
    // now loop through the params and set each one individually
    for(i = 1; i <=4; i++) {
        var key = "Param" + i + "Key";  // build a key string
        set[key] = sourceData[key];     // grab the data and set it
        key = "Param" + i + "Value";    // and repeat
        set[key] = sourceData[key];
    }
    

    然后,将其传递给您的更新:

    jobsCollection.update({
                _id: id
            }, {
                $set: set          // pass the object created above
            }, /* etc. */
    

    如果你不知道Params的数量,你可以:

    1. 发送它
    2. 改用for .. in 循环遍历所有属性

    对于#2:

    for(var key in sourceData) {         
        // you could filter the property names here if you'd like
        // (like if only Params# were important)
        set[key] = sourceData[key];
    } 
    

    【讨论】:

      猜你喜欢
      • 2016-08-03
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 2011-07-10
      • 2014-04-23
      • 2012-10-19
      相关资源
      最近更新 更多