1. 程式人生 > >js中變數和jsp中java程式碼中變數互相訪問解決方案

js中變數和jsp中java程式碼中變數互相訪問解決方案

1。js變數獲取jsp頁面中java程式碼的變數值。

 方法:var JS變數名 = <%=JAVA變數名 %>  

 我們常常會將js檔案和jsp檔案分開寫,在js檔案中,上面的方法似乎不管用了。

也可以通過變通的方法來解決:

a.jsp
   <% String name = "zhangsan" %>
  <input type=”hidden“ name=“a” id="a" value="<%=name%>"
aa.js 
      var n = document.getElementById('a').value;
使用jquery這樣做也更方便
2。java程式碼獲取js變數的值。
 說明:在JSP中;Java部分是在伺服器端執行的;js部分是在客戶端的瀏覽器執行的;二者完全不相干。因此直接在JSP頁面上是無法在js、java和HTML變數之間進行呼叫的。
 變通(解決方案):將js變數放到form中的一個;在後臺從form中取出變數放到隱藏域中;然後提交表單給要呼叫變數的頁面。這個頁面可以就是本身。示例如下:
 bb.jsp頁面: 
    <% String test5 = (String)request.getAttribute("test4"); %>
      <script type="text/javascript"> 

       var test1 = '111'; //定義js變數 
       document.form.test2.value = test1;
       //將js變數的值放到form中的一個隱藏域中 
       var formObj = document.getElementById('passForm');
       formObj.submit();
      </script> 
     <form  method="post" action="aa.jsp" id ="passForm"> 
     <input id = 'test2' type = 'hidden' name="test2"> 

     </form>  
  aa.jsp頁面中的Java程式碼:
  <%
    request.setCharacterEncoding("utf-8");
    String txtMsg = request.getParameter("test2"); 
    out.println(txtMsg);
  %> 

 注:如果同一個頁面自己給自己傳值,aa.jsp和bb.jsp可以為同一頁面。

JS和頁面呼叫JSP變數的一個實際例子如下:

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  
<%  
    String tag=request.getParameter("tag");  
    request.setAttribute("tag",tag);  
 %>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
      
    <title>User login</title>  
      
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    <meta http-equiv="description" content="This is my page">  
   
    <script type="text/javascript" src="jquery-1.8.3.min.js"></script>   
    <script type="text/javascript" >  
        $(function(){                
            //change 驗證碼  
            $("#changeCode").click(function(event){  
                $("#validateCode").attr("src","jsp/MakeCodePicture.jsp?ran"+Math.random());  
                event.preventDefault();  
				$(".thbdisplayName").html("tangtang");
                return false;     
            });  
            
            //send mobile code and change authcode also
            $("#sendCode").click(function(event){
            	alert("ActivationCode is sent to mobile,$basePath");
            	//refresh graph auth code
                $("#validateCode").attr("src","jsp/MakeCodePicture.jsp?ran"+Math.random());  
                event.preventDefault();  
				
                return false;     
            });  
            
            //check authcode is correct 
             $("#passwords").blur(function(){  
                $.post(  
                    "jsp/ValidateCode.jsp",  
                    "inputCode="+$("#passwords").val(),  
                    function(result){  
                        if($.trim(result)=="true"){  
                            $("#cl").html("<span style='color:green'>Authcode Match</span>");      
                        }else{  
                            $("#cl").html("<span style='color:red'>Authcode DisMatch</span>");    
                        }  
                    }  
                );  
            }); 
		$("#thbdisplayID").html("<%=basePath%>");	
        }); 
				
    </script>  
  
  </head>  
    
<body>  
<div class="wrap">  
<!-- main begin-->  
 <div class="main">   
   <div class="sidebarg">  
	  
	  <div class="thbdisplayName" id="thbdisplayID"></div>  
	  
     <form action="UserLogn.jsp" method="get">  
    <div class="login">   
      <dl>  
        <dt class="blues">User Login</dt>  
         <dd><label for="name">UserName:</label>  
            <input type="text" name="auctionuser.username" class="inputh" value="${username}" id="name"/></dd>  
        <dd><label for="password">PassWord:</label>  
            <input type="password" name="auctionuser.userpassword" class="inputh" value="${userpassword}" id="password"/></dd> 
        <dd>  
           <label class="lf" for="passwords">AuthCode:</label>  
           <input type="text" name="inputCode" class="inputh inputs lf" value="" id="passwords"/>  
           <span class="wordp lf"><img id="validateCode" src="jsp/MakeCodePicture.jsp" width="86" height="27" alt="" /></span>  
           <span class="blues lf"><a id="changeCode" href="javascript:void(0);" title=""> refresh</a> <a id="cl"></a></span>  
        
         </dd>  
         <dd><label for="Mobile">MobileNum:</label>  
         <input type="text" name="mobile" class="inputh" value="${mobileNum}" id="mobilenum"/> 
          <span class="wordp lf"><a id="sendCode" href="javascript:void(0);" title="">Send ActivationCode</a> <a id="cl"></a></span></dd>   
           
        <dd class="buttom">  
           <input name="" type="submit" value="submit" class="spbg buttombg f14 lf" />  
           <div class="cl"></div>  
        </dd>  
          
        </dl>  
    </div>  
    </form>  
   </div>  
  <div class="cl"></div>  
 </div>  
<!-- main end-->  
   
<!-- footer begin-->  
</div>  
 <!--footer end-->  
</body>  
</html>