Accessing Javascript variable from ruby

前端 未结 1 1099
無奈伤痛
無奈伤痛 2020-12-12 06:47

Passing data from Ruby to Javascript is easy, for example:



        
1条回答
  •  一生所求
    2020-12-12 07:20

    I'm assuming that you are referring to an embedded Ruby file with something like a js.erb extension.

    Those instance variables, such as @element_id, are used to generate a javascript file to then run client side (ie in the browser)

    It's important to point out here, that the variable @element_id is only used to generate the javascript file then you can essentially consider it "gone" after that javascript file is created.

    That is why you can "pass" Ruby variable values into the javascript file. However, you cannot pass values obtained by the javascript when run client side back to those Ruby variables because they essentially no longer exist as their only purpose was to create the javascript file.

    So the controller action used to generate that file has essentially served it's purpose, and it and it's variables, etc are no longer available.

    Now, it appears that you have a javascript variable, obtained client side, that you want to manipulate before posting it in the js alert.

    You have two choices

    1) You can just manipulate it using pure javascript.

    
    

    2) If for some reason that value needs to be modified based on something like database values that the Rails app has access to, you can post it to a controller and action then return it back to the javascript. (Note: I'm using jQuery library here for efficiency)

    
    

    Controller#update_element_id might be an endpoint for a JS POST request that looks like this.

    def update_element_id
      item = Model.where(element_id: params["old_element_id"]).first
      item.update_attributes(element_id: params["new_element_id"])
      render json: {element_id: item.element_id}
    end
    

    I hope this helps. Glad to provide any additional clarification.

    0 讨论(0)
提交回复
热议问题