Reputation: 2242
I pass a map object called student
to the jsp and the student has some property like NAME,SEX,ADDRESS,PHONE
and so on.Now in the js function I want to get some property from the student.At first,I try to code like this,but it do not work.How to fix my code?
//get the value from the key,I write "${student.NAME}" is OK.
function initSelection(key){
console.log("key:"+key+"value:"+("${student."+key+"}"));
}
$(function() {
initSelection("NAME");
initSelection("SEX");
initSelection("PHONE");
}
Upvotes: 2
Views: 4669
Reputation: 1208
EL code runs at server side, while Javascript code runs in browser.
This line is mixed of server side and client side code, it won't be able to run correctly:
console.log("key:"+key+"value:"+("${student."+key+"}"));
Here the expression of ${student.xxx} will be completed only at client side because key is a JS variable, but it needs to be run at server side to get the expected value as an EL expression.
If you can use JSTL, and don't want to introduce any library that can convert java object to JSON string at server side, this code can be changed to:
var values = {};
<c:forEach var="item" items="${student}">
values['${item.key}'] = '${item.value}';
</c:forEach>
function initSelection(key){
console.log("key:"+key+"value:"+values[key]);
}
$(function() {
initSelection("NAME");
initSelection("SEX");
initSelection("PHONE");
});
At server side the map content is used to generate JS source code that populates a JS variable 'values'. At client side iniSelection() function can get the values in 'values' variable. This code works when there's no single quote character used in student map.
Upvotes: 2
Reputation: 592
You're passing a variable in map and you're accessing it the wrong way in Javascript function.
//TO access value in hashmap using JSTL you need to write
"${student['NAME']}"
.
function initSelection(key){
var name=${student['NAME']};
}
$(function() {
initSelection("NAME");
initSelection("SEX");
initSelection("PHONE");
}
Upvotes: -1