将参数从AJAX传递到JSP页面 [英] Passing a parameter from AJAX to JSP page

查看:286
本文介绍了将参数从AJAX传递到JSP页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将AJAX中的参数传递回我的JSP页面.这是我的示例代码:

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

JS文件:

$(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文件:

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

上面的代码有效-我能够获得参数x.但是,是否可以在同一.JSP页面上将x的值转换为以下格式?

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") %>

或者,获取x的值并将其传递给Java标记<%=%>?

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

此操作的目的是在页面加载时从XML(通过AJAX)获取参数,将参数传递回我的JSP页面,以便我可以使用它动态创建URL(例如,"http://xyz& ; Param ="+ session.getAttribute(" x)+").请注意,必须在jsp页面的Java标签<%= ....%>中定义URL.

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.

推荐答案

您不能在scriptlet中使用Javascript变量.我希望您知道,JSP是在服务器端以及在进行AJAX调用之前执行的.您应该对代码进行一些调整以达到此目的,并在JS中构造URL.像这样

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,

在JSP中,您可以拥有

In JSP, You can have,

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

阅读Ajax Response回调中的上述隐藏元素以构造URL.您可以在任何地方使用构造的url.在这里,我用作表单操作

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;
}

这篇关于将参数从AJAX传递到JSP页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆