0

Is it possible to insert session values in session variable through JavaScript or Jquery?

I have did like session["variable_name"] = "some value"; its not working

Even i tried like <%session["variable_name"] %> = "some value" this is not working either.

But it is possible to read from session.

It says .. there is no keyword named "Session" in Javascript.

Any work around ...

Right now i have done it through Cookies, but i need to do this through session.

Anyone experienced here?

4

4 回答 4

0

If you want to change session variables "live" on a page you can use $.ajax to run a small script that sets session variables in your PHP script, e.g.:

var data = 'sessioninfoiwanttostore='+myJavascriptVar ;
$.ajax({
    url: 'set-session-script.php',
    type: 'POST',
    data: data
})

Then in your PHP script:

<?PHP
session_start() ;
$_SESSION['whatever'] = $_POST['sessioninfoiwanttostore'] ;
?>

Note however this will not change any data on the page that has already been loaded based on your session vars.

于 2012-08-16T06:02:53.980 回答
0

PHP session values are set on the server which means that the only way javascript can manipulate them is if you make a request to another page with ajax to set a value, for example: JS:

$('.updateSession').on('click', function(){
    $.post('updatesession.php', 'name=john', function(){
        alert('Session Updated!');
    })
});

PHP:

<?php
    session_start();
    if($_SERVER['REQUEST_METHOD'] === 'POST'){
        $_SESSION['name'] = $_POST['name'];
    }
?>
于 2012-08-16T06:03:10.367 回答
0

Typically a Session is stored on the server, so javascript and jquery which run in the browser cannot access the session. Reading from the session means the server renders the values into the html from where js can access it.

As cookies live in the browser also, js can access them directly.

As a workaround you can write some sort of ajax call that posts the key/value you want to insert into the session and on the server side a little helper which takes this value and puts it into the session.

于 2012-08-16T06:07:31.833 回答
0

make a webmethod in C# that update the session value which will be access by

[webmethod]

    public static void sesstion_update(session_value)
    {
        httpcontext.current.session["name"] = session_value;
    }

using $.ajax method of Jquery call this web method and pass your value which you want to store in session through data

于 2012-08-16T06:16:44.750 回答