when we use AJAX to call jsp, then the content in jsp will be composed in current page, but the JS in the jsp file can not be parsed.
So we need to abstract the JS to a separate file, then include the js file in the HEAD of current page.
you can refer to JS function appendSpecificJS() below.
As you know, AJAX is an Asynchronous call, so we need to wait for some time to get the content. If we want to get the element value in the JSP file, we need to use window.setTimeout(functionName, delay).
var xmlhttp = getXMLHttpRequest();
function getXMLHttpRequest() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
} else {// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function ajaxValueChange(areaName, errMsg, url) {
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
document.getElementById(areaName).innerHTML = xmlhttp.responseText;
showHint('');
appendSpecificJS();
} else {
showHint(errMsg);
}
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
function baseAction() {
// ajax call here
ajaxValueChange("specificProduct", 'Failed to load specific Product.', "./specificProduct.jsp?servername=" + servername);
// var delayInterval = 1000;
// window.setTimeout(appendSpecificJS, delayInterval);
}
function appendSpecificJS() {
var head = document.getElementsByTagName('HEAD').item(0);
var script = document.createElement("script");
// <input type="hidden" id="jsfilename" name="jsfilename" value="<%=jsFileName %>" /> in [specificProduct.jsp] file
script.src = document.getElementById("jsfilename").value;
script.type="text/javascript";
script.charset="utf-8";
if (isLoadJS) {
head.replaceChild(script, oldNode);
} else {
head.appendChild(script);
}
isLoadJS = true;
oldNode = script;
}
You also can put appendSpecificJS(); in the Ajax response successfully segment to avoid use Timer.
There are two points we should pay attention to:
1) the JS file path can NOT be under /web-root
2) we should fix the JS function name in sepecific product JS, so the base js can invoke them.
eg. specificParam() is defined in specific js file.
To avoid JS error in explorer, when we call specificParam(), we need to add if condition.
function baseSave() {
if (isSaved) {
showHint("This is already saved successfully.");
return;
}
clearHint();
var url = window.document.location.href;
var pos = url.indexOf("?");
var params = url.substr(pos);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
showHint(xmlhttp.responseText);
isSaved = true;
loadReport();
} else {
isSaved = false;
showHint('Failed to save.');
}
}
}
var specificParam = '';
if (isLoadJS) {
specificParam = specificParam();
}
xmlhttp.open("POST", "./persistence.jsp" + params + specificParam, true);
xmlhttp.send();
}
本文详细介绍了如何使用 AJAX 调用 JSP,并在调用过程中遇到的问题及解决策略,包括将 JS 提取到单独文件、等待内容加载、处理错误消息以及在 JSP 中实现特定功能的优化方法。
1133

被折叠的 条评论
为什么被折叠?



