我的coldfusion组件正在返回JSON格式数据。我试图使用Javascript在我的前端访问该数据的值。有人可以帮助我了解如何访问数据值,例如" id"," firs_name"和" last_name"?
我将跟随数据存储在名为tempData的变量中。下面是我得到的JSON结构:
{ "COLUMNS" : [ "id",
"FIRST_NAME",
"LAST_NAME"
],
"DATA" : [ [ "xxxx",
"Jes",
"Abr"
],
[ "xxx2",
"JESSIE",
"YU"
]
]
}
以下是我的ajax电话:
$.ajax({
type: "get",
url: "GROUPSLIST.cfc",
data: {
method: "getNames",
queryString: selectQuery
},
success: function(a) {
alert(a);
},
error: function(a) {
alert(a.responseText);
}
});
答案 0 :(得分:3)
我假设您的回复尚未解析。您可以使用以下内容。
var tempData = '{"COLUMNS":["id","FIRST_NAME","LAST_NAME"],"DATA":[["xxxx","Jes","Abr"],["xxx2","JESSIE","YU"]]}';
//parse response if not already parsed
var respObj = JSON.parse(tempData);
var columns = respObj['COLUMNS'];
//create a column map to index like following
var colMap = {};
for(i = 0; i < columns.length; i++){
colMap[columns[i]] = i;
}
console.log(colMap)
var data = respObj['DATA'];
var text = ''
//use data[i][colMap['id']] to access data inside loop.
for(i = 0; i < data.length; i++){
text += data[i][colMap['id']] + ':' +data[i][colMap['FIRST_NAME']] + ' ' + data[i][colMap['LAST_NAME']] + '<br>';
}
document.getElementById('text').innerHTML = text;
&#13;
<div id="text"></div>
&#13;
答案 1 :(得分:0)
使用数据库查询和按列访问时,这也可能有用(例如:employee_id,employee_name)
步骤-1
// return in serializeJSON format with true
<cffunction name="employeelistJson" returntype="any" returnformat="JSON">
<cfquery name="employeelist" datasource="yourdatasource">
select * from employee
</cfquery>
<cfset setJson = #serializeJSON(employeelist,true)#>
<cfreturn setJson />
</cffunction>
Step-2按名称访问json数据
success: function(response) {
//must be in caps
alert(response.DATA['EMPLOYEEID']);
alert(response.DATA['EMPLOYEENAME']);
},