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

后端 未结 5 1573
慢半拍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:23

    If the array is already defined, you can create a json object by looping through the elements of the array which you can then post to the server, but if you are creating the array as for the case above, just create a json object instead as sugested by Paolo Bergantino

        var saveData = Array();
        saveData["a"] = 2;
        saveData["c"] = 1;
        
        //creating a json object
        var jObject={};
        for(i in saveData)
        {
            jObject[i] = saveData[i];
        }
    
        //Stringify this object and send it to the server
        
        jObject= YAHOO.lang.JSON.stringify(jObject);
        $.ajax({
                type:'post',
               cache:false,
                 url:"salvaPreventivo.php",
                data:{jObject:  jObject}
        });
        
        // reading the data at the server
        
    
        //for jObject= YAHOO.lang.JSON.stringify(jObject); to work,
        //include the follwing files
    
        //
        //
    
        //
        //
    

    Hope this helps

提交回复
热议问题