簡體   English   中英

jQuery:使用ajax-request中的所有數據更新數據庫

[英]jQuery : update the database with all of the data from the ajax-request

我正在嘗試更新數據庫。

因為我這樣做

來自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的索引器樣式屬性訪問器,如下所示。

只是基本顛倒過程。 我不確定數據在您調用update ,所以我在下面的示例sourceData其稱為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];
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM