Convert js Array() to JSon object for use with JQuery .ajax

后端 未结 5 1580
慢半拍i
慢半拍i 2020-11-28 10:13

in my app i need to send an javascript Array object to php script via ajax post. Something like this:

var saveData = Array();
saveData[\"a\"] = 2;
saveData[\         


        
5条回答
  •  庸人自扰
    2020-11-28 10:42

    There is actuly a difference between array object and JSON object. Instead of creating array object and converting it into a json object(with JSON.stringify(arr)) you can do this:

    var sels = //Here is your array of SELECTs
    var json = { };
    
    for(var i = 0, l = sels.length; i < l; i++) {
      json[sels[i].id] = sels[i].value;
    }
    

    There is no need of converting it into JSON because its already a json object. To view the same use json.toSource();

提交回复
热议问题