I have two JSP pages that must use the same javascript. The script attaches a function on an anchor. This function will call a database operation through the controller and service layer when user click on the anchors.
Both JSP pages has these anchors. Hence, it will be good if I can reuse this script in both pages. I am planning to create a JSP page that only has this script and include this pages in both jsp pages. Is this a good practice in re-using a javascript ? Are there any other better ways to do this ?
This is a snippet of the script:
$(document).ready(function(){
$('a[name*="like"]').click(function() {
var hrefName = $(this).attr("name");
var href = $(this);
$.ajax({
type: "POST",
url: "likeARecipe",
data: 'recipeId=' + $(this).attr("title") + '&operation=' + $(this).attr("name"),
success: function() {
if(hrefName == 'unlike')
{
$(href).attr("name","like");
$(href).text("like");
}else {
$(href).attr("name","unlike");
$(href).text("unlike");
}
}
});
return false;
});
});
UPDATE
I decided to put the script into a common.js script. I place this script under scripts/common.js.
I used tag to render the URL to this script.
<spring:url value="/resources/scripts/common.js" var="common_js" />
<script src="${common_js}" type="text/javascript"><jsp:text/></script>
I configure spring to read this script by specfying these resources in a context file:
<resources location="/, classpath:/META-INF/web-resources/" mapping="/resources/**"/>
However, spring did not load the script in the JSP Pages. Any suggestion on a way to trouble shot the problem ?
UPDATE
I found a solution to this problem. I have to modify the script. I enclosed the script inside a function():
(function(){
alert("test");
$(document).ready(function(){
$('a[name*="like"]').click(function() {
var hrefName = $(this).attr("name");
var href = $(this);
$.ajax({
type: "POST",
url: "likeARecipe",
data: 'recipeId=' + $(this).attr("title") + '&operation=' + $(this).attr("name"),
success: function() {
if(hrefName == 'unlike')
{
$(href).attr("name","like");
$(href).text("like");
}else {
$(href).attr("name","unlike");
$(href).text("unlike");
}
}
});
return false;
});
});
})(jQuery);
Create an external .js file and reference it from both JSP pages, like this:
Take a look here: http://www.javascriptkit.com/javatutors/external.shtml