Using Javascript can you get the value from a session attribute set by servlet in the HTML page

后端 未结 4 904
失恋的感觉
失恋的感觉 2020-12-08 04:26

I have a servlet that forwards to a HTML page, using redirect. Because I am using ajax and php on the html page to do other functions. Can turn into a jsp. Is there a way I

4条回答
  •  难免孤独
    2020-12-08 05:14

    No, you can't. JavaScript is executed on the client side (browser), while the session data is stored on the server.

    However, you can expose session variables for JavaScript in several ways:

    • a hidden input field storing the variable as its value and reading it through the DOM API
    • an HTML5 data attribute which you can read through the DOM
    • storing it as a cookie and accessing it through JavaScript
    • injecting it directly in the JS code, if you have it inline

    In JSP you'd have something like:

    
    

    Then in JS:

    // you can find a more efficient way to select the input you want
    var inputs = document.getElementsByTagName("input"), len = inputs.length, i, pONumb;
    for (i = 0; i < len; i++) {
        if (inputs[i].name == "pONumb") {
            pONumb = inputs[i].value;
            break;
        }
    }
    

    or:

    var product = document.getElementById("product"), pONumb;
    pONumb = product.getAttribute("data-prodnumber");
    

    The inline example is the most straightforward, but if you then want to store your JavaScript code as an external resource (the recommended way) it won't be feasible.

    
    

提交回复
热议问题