jquery - Build "data" section of $.ajax method then add variable -
this seems simple syntax issue i'm stuck. building data section $.ajax method (post) this
data = {var1:value1,var2:value2,var3:value3} this work fine.
i need add more key/value pairs have been created in loop (and retrieved html5 session storage), this
moredata = 'var4:value4,var5:value5,var6:value6' my question how add values 'moredata' 'data'
you use jquery extend method this
var originaldata = {val1: value1, val2: value2}; var moredata = {val3: value3, val4: value4, val1: newvalue1}; // did newvalue1 on purpose see below $.extend(originaldata, moredata); // pushes moredata originaldata, update matching values new ones so final value this
orignaldata = {val1: newvalue1, val2: value2, val3: value3, val4: value4}; hope helps can go here more information on jquery extends api
updated answer include code convert string json object
function convertbadjsonstringtogoodjsonobject(badstring){ // expected format not work other format // 'var4:value4,var5:value5,var6:value6' // assumes the value4 , value5 values "actual" string values of key/value pair. if not need put in string. var returndata = {}; // first split on , var keyvalues = badstring.split(","); for(var = 0; < keyvalues.length; i++){ // ok should list of items // 'var4:value4 // need split on : var keyvaluepair = keyvalues[i]; var pair = keyvaluepair.split(":"); if (pair.length === 2){ var key = pair[0]; var value = pair[1]; // convert json object var stringifiedjson = '{"' + key + '":"' + value + '"}'; // should // '{"var4":"value4"}' try{ var newproperjsonobject = json.parse(stringifiedjson); $.extend(returndata, newproperjsonobject); } catch (ex) { // went wrong parse, perhaps original format wasnt right. } } // else not valid pair } return returndata; } var badstring = 'var4:value4,var5:value5,var6:value6'; var goodobject = convertbadjsonstringtogoodjsonobject(badstring); console.log(goodobject); a few things explain answer above. first, json format specific format data transport. while javascript uses lazy version of uses, json.parse expects string in "real" json format. means keys need surrounded double-quotes. in javascript can define object {val: value1} , life good. for json.parse string need '{"val1":"value1"}'. if pass '{val1:value1}'. break , throw javascript exception. why have surrounded in try catch.
i made function purposely verbose feel free ask questions on it. once string object converted $.extend function work explained earlier.
Comments
Post a Comment