简体   繁体   中英

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

am trying to update database.

For that iam doing like this

From js code

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

in node.js side

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

in record.names and record.scripttype getting proper values.

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........
  ............
 }

Since the property names are dynamic, you'll need to use the indexer-style property accessor of JavaScript as shown below.

Just reverse the process basically. I'm not sure where the data is located at the point you're calling update , so I called it sourceData in the example below;

// 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];
}

then, pass it to your update:

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

If you don't know the count of Params , you could:

  1. send it
  2. use instead for .. in to loop through all the properties

For #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];
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM