I’ve tried to put an object in a session inside a servlet and read it inside a javascript code. Actually that works, but after converting the normal javascript code to AJAX, it couldn’t recognize it any more.
This is the servlet’s code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject object = new JSONObject();
object.put("A","A");
request.getSession().setAttribute("json", object.toJSONString());
}
And I want to recieve it in the following AJAX code.
<script type="text/javascript">
function runAjax(){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
var json = <%=session.getAttribute("json")%>
alert(json);
}
}
ajax.open("GET", "servlet", true);
ajax.send();
}
</script>
json content is null.
Any help please?
Thanks very much.
JavaScript executes in the browser. JSP scriptlet executes on the server.
So when you make a request to the page containing the above JavaScript code, the HTML is generated by the server. The server executes the following scriptlet code:
<%=session.getAttribute("json")%>. Since, at this moment, the session attribute doesn’t exist, the generated HTML is:Then this HTML/JS code is downloaded by the browser, and the JS code is executed in the browser. The browser sends an AJAX request to the server, and when the response comes back, the browser executes the following function:
So obviously, what is displayed in the allert box is
null.