0

I have the following code sample which was written in the JSP. But it is not working. I have tried that code snippet from the following links. But it didn't help me to solve the problem.

Pass a JSP variable as parameter to javascript function

Passing Jsp variable to javascript as a function parameter

< c:forEach items="${items}" var="item">

   <div onclick="myOnClick('<%=item%>')">${item.title}</div>

< /c>

function myOnClick(item){
    console.log(JSON.stringify(item));
}

Actually I am getting an error in the eclipse that "item cannot be resolved to a variable" for the JSP code.

I tried the below one code

      <div onclick="myOnClick(${item})">${item.title}</div>

It was throwing "Syntax error:illegal character" error.

Need help to fix this issue. Thank you.

8
  • 1
    Why use <%=item%> instead of ${item}?? Anyway, what you insert is a string (you even quoted it with '), which is retrieved by calling item.toString(), so what is it you expect that stringify() call to do? I mean, it's already a string, and very likely not a JSON string, unless you implemented toString() to return JSON. Commented May 28, 2016 at 18:46
  • Actually I am getting an error in the eclipse that "item cannot be resolved to a variable". That is my problem. That method myOnClick() is a temporary method. Don't concentrate on that method implementation. I was asking about the JSP code Commented May 28, 2016 at 18:50
  • That's a totally different question. Use ${item}. Commented May 28, 2016 at 18:57
  • I tried ${item} also. It was throwing "Syntax error:illegal character" error Commented May 28, 2016 at 19:04
  • On the ${item} when ${items} is working fine on the line above?? I find that very hard to believe. Or are you now talking about the web browser, not the JSP (because you forgot the add the ' quotes)?? Commented May 28, 2016 at 19:06

1 Answer 1

0

I found the answer by my own from the following link.

How to access a java object in javascript from JSP?

That is what exactly I was doing in the code. I am getting the Java objects and I am mapping them to the HTML. Once they mapped I wan unable to access them from javascript. But in the above link they have provided the solution to the problem. So we have to call a web service to get the actual object. Thank you @LeleDumbo for providing the answer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.