2013-03-20 111 views
56

在代碼隱藏中,我用一些數據設置了Session如何訪問會話變量並在JavaScript中設置它們?

Session["usedData"] = "sample data"; 

,問題是我怎樣才能得到會話值(在我的例子;「樣本數據」)在JavaScript,並設置Session["usedData"]一個新的價值?

+2

請說明是ASP.Net MVC還是Webforms。如果MVC,你可以直接訪問它的JavaScript。如果webforms,你可以暫時添加到ViewState [] – Fendy 2013-03-20 09:19:43

+0

我使用WebForms,爲什麼我不能訪問Session變量並將其設置爲一個值? – 2013-04-29 09:31:32

+1

沒有太深入到WebForms中,直接訪問WebForm中的Session對我來說是新的(儘管這很可能是不好的做法)。 Session在服務器端(webserver/iis),而javascript在客戶端(瀏覽器)。您需要特定的請求才能在會話中觸發更改。簡而言之,您可以使用ajax(簡單實現的jQuery)和webservice從javascript更新會話。 – Fendy 2013-04-29 10:05:55

回答

49

訪問&分配使用Javascript會話變量:

分配ASP.NET會話變量使用Javascript:

<script type="text/javascript"> 
function SetUserName() 
{ 
    var userName = "Shekhar Shete"; 
    '<%Session["UserName"] = "' + userName + '"; %>'; 
    alert('<%=Session["UserName"] %>'); 
} 
</script> 

訪問ASP.NET會話變量使用Javascript:

<script type="text/javascript"> 
    function GetUserName() 
    { 

     var username = '<%= Session["UserName"] %>'; 
     alert(username); 
    } 
</script> 
+0

我們可以檢索.cs文件中的這個Session值嗎? – 2014-01-21 14:34:10

+0

是的offcourse ..! – 2014-01-22 13:17:52

+4

我試過了你代碼和我在我的代碼中訪問它時得到的輸出結果是'+ userName +' – 2014-01-23 04:16:56

10

嘗試這個

var sessionValue = '<%=Session["usedData"]%>' 
+0

謝謝,這很好:)但我想設置會話值,這可能嗎? – 2013-03-20 09:21:15

+2

我認爲你不能 – 2013-03-20 09:22:01

+0

@MehmetInce,設置會話值,你會發送值到服務器通過職位或獲取並讓服務器處理請求。沒有什麼能阻止你通過ajax做這個請求。 – 2013-03-20 09:31:20

14

你不能在JavaScript中直接訪問Session

你可以做一個隱藏字段,並把它傳遞到您的網頁,然後在代碼隱藏文件中使用JavaScript通過document.getElementById

+1

不正確,你還記得考試嗎? JS中的sessionStorage;)。 – mattytommo 2013-03-20 09:24:34

+0

哈哈 - 我得到了localStorage的問題 - 以防萬一用戶返回頁面! ;) – 2013-03-20 09:26:37

+0

這種方法存在風險,因爲用戶可以使用瀏覽器開發工具輕鬆更改隱藏字段的值。 – 2016-07-17 06:02:36

3

指定值來檢索對象的隱藏字段。在JavaScript中像訪問一般的HTML控件一樣訪問這個值。

5

假設你的意思是「客戶端JavaScript」 - 那麼你不能,至少不能直接。

會話數據存儲在服務器上,因此客戶端代碼在與服務器通信時無法看到它。

要訪問它,你必須做出一個HTTP請求,有一個服務器端的程序修改/讀取&返回數據。

+0

如果我不能直接訪問,我的lasy機會就是使用http請求:( – 2013-03-20 09:26:40

8

Javascript無法直接設置會話值。 對於從JavaScript設置會話值我做ajax調用如下。

Check Online

在ASPX文件或HTML,

<script type="text/javascript"> 
$(function(){ 
    //Getting values from session and saving in javascript variable. 
    // But this will be executed only at document.ready. 
    var firstName = '<%= Session["FirstName"] ?? "" %>'; 
    var lastName = '<%= Session["LastName"] ?? "" %>'; 

    $("#FirstName").val(firstName); 
    $("#LastName").val(lastName); 

    $('Button').click(function(){ 
    //Posting values to save in session 
    $.post(document.URL+'?mode=ajax', 
    {'FirstName':$("#FirstName").val(), 
    'LastName':$("#LastName").val() 
    }); 
    }); 

}); 

在服務器端,

protected void Page_Load(object sender, EventArgs e) 
{ 
     if(Request.QueryString["mode"] != null && Request.QueryString["mode"] == "ajax") 
     { 
     //Saving the variables in session. Variables are posted by ajax. 
     Session["FirstName"] = Request.Form["FirstName"] ?? ""; 
     Session["LastName"] = Request.Form["LastName"] ?? ""; 
     } 
} 

爲獲得會話值,由謝加和拉傑夫

var firstName = '<%= Session["FirstName"] ?? "" %>'; 

希望這有助於。

1

我一直在尋找解決這個問題,直到我發現了訪問會話變量,一個非常簡單的解決方案,假設你使用服務器端的一個PHP文件。希望這回答了這個問題的一部分:

訪問會話值

<script type="text/javascript">   
    var value = <?php echo $_SESSION['key']; ?>; 
    console.log(value); 
</script> 

編輯:下面最好的例子,你可以嘗試phpfiddle.org,在「碼域」選項卡

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <?php 
    $_SESSION['key'] = 10; 
    $i = $_SESSION['key']; 
    ?> 
</head> 
<body> 
    <p id="affichage">hello</p> 

    <script type="text/javascript"> 
    var value = <?php echo $i; ?>; 
    $("#affichage").html(value); 
    </script> 

</body> 
</html> 

設置會話值

將它傳遞給任何變量,你可以你想。例如,

$you = 13; 
$_SESSION['user_id'] = $you; 

這應該工作,沒有測試它。

+0

返回錯誤 – 2016-03-13 19:53:23

+0

您可能忘記替換'key' – Matthieu 2016-06-02 13:18:26

+0

nope,「Uncaught SyntaxError:Unexpected token <」 – 2016-07-06 17:39:46

1

你也可以設置變量的財產和JS調用它:

在服務器端:

Protected ReadOnly Property wasFieldEditedStatus() As Boolean 
    Get 
     Return If((wasFieldEdited), "true", "false") 
    End Get 
End Property 

然後在JavaScript:

alert("The wasFieldEdited Value: <%= wasFieldEditedStatus %>"); 
2

你可以從Javascript設置會話端會話變量。如果要做到這一點,你需要創建一個AJAXPOST服務器更新本但如果汽車的選擇是一個重大的事件很可能就是更容易POST這一點。

1

代碼首先創建一個方法的背後設置會話:

[System.Web.Services.WebMethod] 
public static void SetSession(int id) 
{ 
    Page objp = new Page(); 
    objp.Session["IdBalanceSheet"] = id; 
} 

然後從客戶端調用它:

function ChangeSession(values) { 
    PageMethods.SetSession(values); 
    } 

你應該設置的EnablePageMethods爲true:

<asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release" LoadScriptsBeforeUI="true"></asp:ScriptManager> 
0

這是一個作弊,但你可以做到這一點,將值作爲參數發送到服務器端

<script> 
var myVar = "hello" 
window.location.href = window.location.href.replace(/[\?#].*|$/, "?param=" + myVar); //Send the variable to the server side 
</script> 

,並從服務器端,檢索參數

string myVar = Request.QueryString["param"]; 
Session["SessionName"] = myVar; 

希望這有助於

1

如果你想閱讀你javascript.This代碼幫助會話值。

<script type='text/javascript'> var userID='@Session["userID"]'; </script>

相關問題