[英]Set a JavaScript variable from JSP (server side) bwithout reloading the page
我想从JSP设置一个JavaScript变量,而不会导致整个页面重新加载。 我现在的代码设置了变量,但是作为副作用重新加载了整个页面。
example.jsp:
<html>
<select name="country" id="country"onchange="getCountryI()">
<option value="">Select</option>
<option value="india">India</option>
<option value="aus">Austrila</option>
<option value="uk">U.K</option>
<option value="eng">England</option>
<option value="westindies">West-Indies</option>
</select>
</html>
<script>
function getCountryI() {
alert(3);
var id = document.getElementById("country").value;
window.location.replace("example.jsp?name=" + id);
}
</script>
<%
String value = request.getParameter("name");
System.out.println("value is" + value);
out.println("valuevaluevalue" + value);
%>
我认为问题不在<%%>内部。 事件onChange已被调用,并且此代码正在“刷新”页面。 (实际更改位置)
window.location.replace("example.jsp?name=" + id);
尝试调试。
这部分无效:
<script>
function getCountryI() {
alert(3);
var id = document.getElementById("country").value;
window.location.replace("example.jsp?name=" + id);
}
<%
String value = request.getParameter("name");
System.out.println("value is" + value);
out.println("valuevaluevalue" + value);
%>
</script>
刷新后, out.println
将在渲染的页面中添加无效的脚本内容,也不会显示。
<% %>
部分应从脚本中移出,如下所示:
<script>
function getCountryI() {
alert(3);
var id = document.getElementById("country").value;
window.location.replace("example.jsp?name=" + id);
}
</script>
<%
String value = request.getParameter("name");
System.out.println("value is" + value);
out.println("valuevaluevalue" + value);
%>
下载页面后,从服务器更新本地(页面内)变量的唯一方法是:
a)重新加载页面,或b)使用AJAX(最好是JSON / P)来获取变量。
HTTP是无会话的,这意味着除非浏览器启动联系,否则服务器端无法向最终用户浏览器上的页面提供数据。 (不包括Web /浏览器套接字,因为它们仅是HTML5。您是否真的希望服务器端保留所有曾经需要响应的浏览器列表并编写代码以使它们老化?如果您这样做,请继续-但只用AJAX会更容易。)
您可以使用老式Ajax:
<form action="..." method="..." target="foo">
...
<input type="submit" value="Submit">
</form>
<iframe id="foo"></iframe>
您可以将onload事件处理程序附加到iframe
以便提取所需的任何信息:
var foo = null;
var iframe = document.getElementById("foo");
iframe.addEventListener("load", function() {
var win = iframe.contentWindow || iframe.contentDocument;
foo = win.foo
});
IFRAME中的响应可以具有一个普通的<script>
标记,该标记在该文档中设置了一个全局变量,您可以从父窗口访问该变量。
编辑:这里的关键是FORM标记上的target
属性,包含IFRAME上id
的值。 这将导致表单提交到IFRAME,并将响应加载到IFRAME中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.