문제

For example I've got some variable in java class, how to I acess it with jquery? If I had a scriplet, I would've done something like

<% SomeVariableClass var = SomeVariableClass.getInstance()%>

So, how do I do the same with jquery?

 var variable = ?

Or do I need to call a method from servlet or something?

도움이 되었습니까?

해결책

In your code you are just creating a variable for your JSP.

You will have access to it by creating a element in your answer. something like:

<div id="var">value</div>   <---JSP have to reply that.

<div id="var"><%= var.value() %></div>   <--- exemple of JSP code to produce the answer u need.

And then you can use jquery $("#var") <--- that runs in the browser.

You will have to use CSS to hide it if you want.

or you can use Ajax, as an option.

Ajax:

$.ajax({
        type: 'GET',
        url: 'xxxx',   <-- your url
        success: function(reply) {
                    Alert(reply); <-- just for you to see the reply, u can do whatever..
                 }
       });

$(reply), could help to parse or access stuff.

but to use this option, ur URL needs to point to a resource that is able to reply something like:

<div id="var">value</div> <---JSP have to reply that.

Resource example:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body> 
<% SomeVariableClass var = SomeVariableClass.getInstance()%>
<div id="var"><%=var.getValue()%></div>
</body>

cheers

다른 팁

If you want to access some variable from java class without adding scriptlets in JSP, you need to setup a servlet which will return you the data and from jQuery you need to make a call to that service.

If you can add scriplets to JSP, then Inside the JSP add the script under a div.

for example :

<div id="java_content">
 <% SomeVariableClass var = SomeVariableClass.getInstance();
    var.callAppropriateMethod();  
    // which will return you the data
%></div>

in Jquery, you can access it using:

var javaContent = $("#java_content").html();

It will return you the content, Now you can use javaContent javascript variable as you wish :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top