2016-12-25 32 views
0

我是node.js的新手。 我有兩個html文件和一個共享的common.js。 在index1.html中,當點擊錨點按鈕時,它會調用common.js(它更新測試變量)的changetest()函數。 現在我想在index2.html中使用更新後的變量。 但是index2.html選擇了測試的原始值。 (這可能是因爲在新頁面index2.html重新加載common.js) 請幫助什麼可以是在index2.html中傳遞和接收測試值的好方法。什麼是訪問nodejs中兩個html文件之間的共享javascript變量的最佳方式

Index1.html

<html> 
    <head> 
     <script type="text/javascript" src="common.js"></script> 
    </head> 
    <body> 
     <h1>Sample Page</h1> 
     <a href="index2.html" onclick="changetest()">Navigate</a> 
    </body> 
</html> 

common.js

var test="abc"; 

function changetest(){ 
    test = "xyz"; 
} 

index2.html

<html> 
    <head> 
     <script type="text/javascript" src="common.js"></script> 
    </head> 
    <body> 
     <h1>Sample Page2</h1> 
     <a href="#"><script>document.write(test)</script></a> 
    </body> 
</html> 
+0

http://stackoverflow.com/questions/3737062/managing-sessions-in-node-js – RobE

回答

0

我會建議使用https://developer.mozilla.org/en/docs/Web/API/Window/localStorage

有了它,你可以輕鬆地設置和從用戶瀏覽器獲取數據。

要使用它只是做這樣

localStorage.setItem('test', 'My test value');

alert("test= " + localStorage.getItem("test"));

https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage

希望這有助於。

+0

感謝您的建議。但我擔心如果用戶禁用本地存儲支持。 – shail

+0

https://blog.yell.com/2016/04/just-many-web-users-disable-cookies-javascript/那麼在這種情況下,你不得不擔心用戶禁用JS和其他東西。禁用此選項的用戶不太可能。 –

相關問題