我正在通过Jquery Ready函数进行一些Ajax调用。在后端处理之后,我在Session中设置了很少的变量。当回到我的相同JSP页面时,我试图打印那些变量但是当页面第一次加载时,这些变量将变为空。如果我重新加载页面,我能够看到变量的值。我不确定我哪里错了。
Ajax调用JSP
jQuery(document).ready(function() {
var myToy = 'B';
var url="/myBuysAjaxCall.ac?&myToy="+myToy;
if(window.XMLHttpRequest) {
AJAX = new XMLHttpRequest();
} else if(window.ActiveXObject) {
if(ms_xmlhttp) {
AJAX = new ActiveXObject(ms_xmlhttp);
} else {
var versions=["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
for(var i=0; i<versions.length; i++) {
try {
AJAX = new ActiveXObject(versions[i]);
if(AJAX) {
ms_xmlhttp = versions[i];
}
} catch(e) {
//do nothing. go to next version and try it.
}
}
}
}
AJAX.onreadystatechange = processMyToy;
AJAX.open("GET", url, true);
console.log("Ajax call made..");
AJAX.send(null);
});
function processMyToy() {
if (AJAX.readyState == 4) { // Complete
if (AJAX.status == 200) { // OK response
var returnedValue = AJAX.responseText;
console.log("Something came in Response ");
var obj1FromSession= '<c:out value="${obj1FromSession}"/>';
var obj2FromSession= '<c:out value="${obj2FromSession}"/>';
var obj3FromSession= '<c:out value="${obj3FromSession}"/>';
console.log(obj1FromSession);
console.log(obj2FromSession);
console.log(obj3FromSession);
}
}
});
后端代码
public void loadandProcessMyToy() throws Exception{
Context contextObj = ContextHelper.getContext();
String myToy = (String) contextObj.getObjectFromRequest("myToy");
If Condition{
String obj1FromSession="Hello 1";
String obj2FromSession="Hello 2";
String obj3FromSession="Hello 3";
ContextHelper.getContext().setObjectInSession("obj1FromSession",obj1FromSession);
ContextHelper.getContext().setObjectInSession("obj2FromSession",obj2FromSession);
ContextHelper.getContext().setObjectInSession("obj3FromSession",obj3FromSession);
}
}
注意: - 当第一次加载页面时,它在Ajax响应部分中显示为空。在页面重新加载(通过F5)时,按预期打印Hello1,Hello2 ..
我想在第一次加载时看到值。请帮忙。