简体   繁体   中英

Set session attribute using javascript

I'm using jqueryui autocomplete combobox in my jsp page. I need to set selected value of combo-box to the HttpSession .

I tried as below.

this._on(this.input, {
    autocompleteselect: function (event, ui) {
        // alert(ui.item.value);
        var value = ui.item.value;
        <% session.setAttribute("comboboxvalue",value); %>  

        ui.item.option.selected = true;
        this._trigger("select", event, {
            item: ui.item.option
        });
}

Problem with this way is that code don't recognize value param.

How can I solve this and set session attribute using javascript ?

You might misunderstand that jsp and javascript existed on same file. Yes but JSP part compiles on server side itself comes to client .

The code inbetween <% %> executes on serverside.

You can't do that with Javascript .

You need to make a server request(There are forms,Ajax,url..etc) for that.

Java script is a client side technology. Its not possible to set any session variables from Java script.

You can do this using Ajax. Through Ajax you have to send a request to the server asynchronously and then add the data to the session from within the servlet.

You cannot set session values in JavaScript.

For your case, you can trigger an AJAX call for onChange event in your select box. You can simply send the select box value to server and place it in session.

Here is how I achieved my task successfully.

I have created a new servlet and trigger an AJAX call as below. Then I set comboboxvalue to session from servlet.

this._on( this.input, {
    autocompleteselect: function( event, ui ) {
        $.ajax({
        type: 'POST',
        url: 'AjaxServlet',
        dataType : 'json',
        data: { comboboxvalue : ui.item.value  }
        });
        ui.item.option.selected = true;
        this._trigger( "select", event, {
            item: ui.item.option
        });
    },

    autocompletechange: "_removeIfInvalid"
});

您可以使用javaScript操作表单将args投递到servlet类,并在此servlet类中添加setSession。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM