Reputation: 12683
I am trying to pass an object to a javascript function which should trigger when a link is clicked. But unfortunately I am not able to get it working.
Here is the code on my jsp file for the same:
<script type="text/javascript">
$(document).ready(function() {
function tryToDoItTwice(obj) {
var check = obj;
if(check == null) {
return true;
}
else {
alert("You're not allowed to do this twice!");
return false;
}
}
});
</script>
<a href="<c:url value="/somepath" />" onclick="javascript: tryToDoItTwice(${foo});">Try to do it twice</a>
Here foo
refers to an object of type Foo
.
Could someone help me understand what am I doing wrong here?
EDIT: Foo
is a java object. and ${foo}
is a reference variable referring to Foo
java object.
Thanks.
Upvotes: 0
Views: 3384
Reputation: 12782
You can't pass a JAVA object directly to javascript. Either you need to return as JSON ( look up GSON or Jackson for converting object to JSON ) or pass variables( not object ) to the function.
Upvotes: 1
Reputation: 28699
Your check
variable is locally scoped to that function so it will be redeclared each time the function is called (not storing your value the next time it's clicked.
You need to expand the scope of your variable.
var check = null;
$(document).ready(function() {
function tryToDoItTwice(obj) {
check = obj;
if(check == null) {
return true;
}
else {
alert("You're not allowed to do this twice!");
return false;
}
}
});
Also, if foo
exists elsewhere, you probably just want to pass it in like this:
<a href="<c:url value="/somepath" />" onclick="javascript: tryToDoItTwice(foo);">Try to do it twice</a>
Upvotes: 3