简体   繁体   中英

session attribute not being set until I refresh thepage

I have some code:

$(document).ready(function(){    
   $(":button").click(function(){
       var formData = {"field1":field1, "oper1":oper1, "value1":value1, "field2":field2, "oper2":oper2, "value2":value2, "field3":field3, "oper3":oper3, "value3":value3};
            $.post("<%=request.getRequestURL().toString()%>getInfo.jsp", formData, function(response){alertHere(response)});    
        })
})

function alertHere(response){
        alert("Post successful");
        alert(response);
        renderResults();
}

that posts form data and queries for the data and sets the session attribute with

 session.setAttribute("directoryString", xml);

when a button is clicked. In the response function, renderResults is called, which grabs the returned xml:

 function renderResults(){
       alert("inside renderResults()");
       element = document.getElementById("person");
       xmlString = '<%=session.getAttribute("directoryString")%>';
       console.log('XML String: ' + xmlString);

The rest of the function is written to parse out the xml and display it on the page.

My problem is that when I first go to the page and post data, the xmlString variable is null. When I refresh the page and go back to "Page Source" in my web console, the variable is set correctly. I'm not exactly sure what's going on. Is it possible that my function is trying to call the session attribute before it's set?

PS I know that scriplets aren't the best way of doing it, but that's the way we do it around here.

<%=session.getAttribute("directoryString")%> will only be evaluated when the JSP is rendered into the HTML page. Once the rendered HTML is in the browser, it can only be changed either by:

  • reloading the page
  • JavaScript.

Make an ajax call to get the updated value of the attribute and update the variable (for example, you can set document.myXmlString = '' and use that value in your renderResults .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM