Passing a parameter from AJAX to JSP page

浪子不回头ぞ 提交于 2019-12-25 08:09:13

问题


I am trying to pass a parameter from AJAX back to my JSP page. Here is my sample code:

JS File:

$(document).ready(function() { 
            $.ajax({
            type: "GET",
            url: "URL...",
            dataType: "xml",
            success: function(xml) {
                $(xml).find('Rowsets').each(function(){ 
                            var x = $(this).find('Auto_Id').text() // Assign data from Auto_Id into variable x
                    document.form.y.value = x; // Pass the parameter back to the JSP page
                    });
                }
    });
});

.JSP File:

<FORM name="form"><input name="y" value="" /></FORM> //value left blank for AJAX to auto-populate

The above code works - I am able to get the parameter x. However, is it possible to get the value of x into the following format on the same .JSP page?

<%= session.getAttribute("x") %>

Or, get the value of x and pass it into the java tags <%= %>?

The purpose of this is to grab the parameter from the XML (via AJAX) on page load, pass a parameter back to my JSP page so that I can use it to dynamically create a URL (e.g. "http://xyz&Param=" + session.getAttribute("x") + ""). Note that the URL has to be defined in java tags <%= .... %> of the jsp page.


回答1:


You can't use Javascript variable in scriptlets. I hope you know that, JSPs are executed at server side and before making your AJAX call. You should do some tweaks in your code to achive this, construct the URL in JS. Like this,

In JSP, You can have,

<input type='hidden' value='<%=dynamicallyCreatedURL%>' id='dynamicallyCreatedURL'/>

Read the above hidden element in Ajax Response callback to construct the URL. You can use constructed url in anywhere. Here I used as form action

$(xml).find('Rowsets').each(function(){
    var x = $(this).find('Auto_Id').text() // Assign data from Auto_Id into variable
    document.form.y.value = x; // Pass the parameter back to the JSP page 

    //Here construct the URL and set as forma action
   var dynamicallyCreatedURL = document.getElementById('dynamicallyCreatedURL').value+'?param='+x; 
document.form.action = dynamicallyCreatedURL;
}


来源:https://stackoverflow.com/questions/9223583/passing-a-parameter-from-ajax-to-jsp-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!