I am writing a site using JSP. I have included a code snippet below.
The problem I’m having is that every time the page loads the addBookmark() method inside of the javascript is executed but I do not see the alert. When I press the button, I see the alert but the addBookmark() method is not called. What is causing this strange behavior?
<% User user = new User() %>
<script type="text/javascript">
function add()
{
<% user.addBookmark(); %>
alert("addBookmark");
}
</script>
<button type="button" style="float: right" onclick="add()">Bookmark</button>
Thanks is advance!
Because JSP doesn’t communicate directly with the browser, nor does it have any knowledge of what the browser does with the page and what the user does. It’s just a simple interpreter that walks through your code and looks for
<%. Any code that’s between<%and%>gets executed, and the rest simply gets written to the browser. That means that your JavaScript will not get read by the JSP interpreter, and the server will simply add the bookmark.What you are looking for is a request to the server to actually add the bookmark. Something like
mypage.jsp?addBookmark=truewhich adds the bookmark.