basically I have 2 problems with javascript and jsp file. First one concerns fact that I can’t include externall js file into jsp file. Basic structure of my project looks something like this:
system.web
|
WebContent
|
js
|
nowa_postac.js
|
jsp
|
nowa_postac.jsp
nowa_postac.js has only
init = function() {
test();
}
function test() {
var myObject = JSON.parse('${gson}', null);
alert(myObject.rasy.rasaList.length);
alert(document.getElementById("testowy").id);
}
I include javascript inside nowa_postac.jsp with:
<script type="text/javascript" src="${pageContext.request.contextPath}/js/nowa_postac.js"></script>
but I can’t call any function from nowa_postac.js in jsp file and
src="<c:url value="/js/nowa_postac.js"
seems to be not working either…
test() returns nothing but alert(test) returns text, so javascript file is loaded…Also, everything works fine when test() is inside jsp file.
The second problem is about how to initialize function after the jsp page is loaded;
<body onload='init()'>
is not good here because in init() I need to refer to some objects created in jsp…
Thanks for any help
I use jQuery to answer this question. First I have an external .txt file with the name includedScripts.txt which has the following format:
For example:
Note that nowaPostAc.js will be residing in a subfolder called Scripts.
Next I load jQuery (I’m assuming you know how to do this, if not you can read up on http://www.learningjquery.com/2006/09/introducing-document-ready#more-5) and in my jQuery file I have the following:
You will more than likely need to edit the lines:
to possibly read something like:
What the script does (in conjunction with the includedScripts.txt file) is allow you to specify a different script to be loaded based on the page. This of course, assumes that you have a singular script that is loaded on all pages, for example:
which would have the above code (Load Additional Scripts).
This works for me, you’ll have to do some tweaking – let me know if you get through.