garyv
garyv

Reputation: 187

How to convert string returned by AJAX into javascript array of objects

I'm using jqGrid and would like to use the ajax return from Coldfusion to build the colModel array.

When I create the array cm on the client like below, this works.

function subTab(obj,id,tab){
var param={id:id,tab:tab}
http('POST','cfc/view/'+obj+'.cfc?method=view',subTab_RTN,param);
}
function subTab_RTN(obj){
$("#detail").html(obj.html);
if(obj.grid.display){
var cm;
switch(obj.grid.tab){
case "docs":
cm=[{name:'contactID',index:'contactID',hidden:true},
{name:'docName',index:'docName',width:200,label:'Document Name'},
{name:'docType',index:'docType',width:200,label:'Document Type'},
{name:'campaign',index:'campaign',width:200,label:'Campaign'},
{name:'campaignCode',index:'campaignCode',width:125,label:'Campaign Code'},
{name:'campaignType',index:'campaignType',width:125,label:'Campaign Type'},
{name:'downloadDate',index:'downloadDate',width:125,label:'Download     Date',formatter:'date'}];
break;
}
$("#subTabGridTbl").jqGrid({
url:obj.grid.url, 
datatype: "json", 
colModel:cm,
...

I would prefer however to create the array on the server like:

 <cfset rtn.grid.cols="[{name:'contactID',index:'contactID',hidden:true},
 {name:'docName',index:'docName',width:200,label:'Document Name'},
 {name:'docType',index:'docType',width:200,label:'Document Type'},
 {name:'campaign',index:'campaign',width:200,label:'Campaign'},
 {name:'campaignCode',index:'campaignCode',width:125,label:'Campaign Code'},
 {name:'campaignType',index:'campaignType',width:125,label:'Campaign Type'},
 {name:'downloadDate',index:'downloadDate',width:125,label:'Download Date',formatter:'date'}]" />

and then use the returned obj (obj.grid.cols) to build the array.

Thanks for your help. Gary

Upvotes: 1

Views: 1526

Answers (1)

Sean Walsh
Sean Walsh

Reputation: 8344

JSON.parse() is supported in most major browsers. If you need to support IE7 and below, I believe you can use jQuery.parseJSON() to get the same result. Both methods require a well-formed JSON string.

As an aside, I'd recommend creating your array as a native CF array of structs and then using serializeJSON() to convert it to a JSON string. This will help minimize any issues you'll run into by trying to write the JSON string by hand.

Upvotes: 3

Related Questions