Link to home
Start Free TrialLog in
Avatar of richardluo
richardluo

asked on

Can I use javabean in a javascript function ?

Hi,

  I want to access javabean from javascript function, I don't know if it's possible. please give a sample code if it's possible.


Thxs
ASKER CERTIFIED SOLUTION
Avatar of jimmack
jimmack

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of richardluo
richardluo

ASKER

Thanks jimmack for the comments. One more question, how to pass a javascript variable to a jsp function. Here are a part of my code:

function test(){
.....
var catId = document.form1.List1.options[document.form1.List1.selectedIndex].value;
 <% CategoryBean cb = Utilites.getCategoryWithID(application,catId);%>
.....
}

I need function getCategoryWithID to know variable catId which is javascript variable now. Compiler generate an error for catId.
Sorry to say that I don't think you can do that.  The problem is that the test() function will execute in the clients browser (locally), but the JSP you're including has already been compiled and executed by the time the page is loaded into the browser.

If you need to call the getCategoryWithID() method on a button press (for example), then the onclick needs to access the server again (so that getCategoryWithID() can get the results on the server and prepare the new page).

Unfortunately it's the same problem whichever way round you do it, JavaScript execute on the client and JSP/Servlets execute on the server.
Thanks Jim for your help !
;-)
Hi Jim,

  One more basic question, I have the following javascript code:

function test()
{
          <% int index=-1;%>
          for (var i=0; i< 10;i++)
          {
             <% index=index + 1;%>
             alert("<%= index%>");
                  }
}

When I run this function, index shown in alert window is alway "0", it suppose to be: 0,1,2,3..., something wrong with this code ?

Thanks in advance.

Richard
Yes.  The problem is with the way you've mixed the JSP and JavaScript.  When you load the page into your browser, have a look at the source.

You'll probably find it isn't what you were hoping for.  The JSP is compiled and executed before the HTML (including the JavaScript) is sent to the browser, so you'll probably see:

function test()
{
    for (var i = 0; i < 10; i++)
    {
        alert("0");
    }
}

That's because the JSP lines were translated (they don't get included in the HTML), so index was set to -1, then incremented and this value was put into the alert string.
Thanks a lot Jim ! You have a nice weekend !

Richard
You too :-)