简体   繁体   English

如何在Rails视图上的ruby中访问javascript变量

[英]how to access javascript variable in ruby on rails view

We have a javascript code in which url of selected image is obtained in javascript variable (src). 我们有一个javascript代码,其中在javascript变量(src)中获得所选图像的url。 We want to access src var in rails view to obtain the id of the selected image.Tried this by using Ajax where we tried passing the url to var created in controller but somehow the ajax call isn't working,therefore controller var always show nil value. 我们想在rails视图中访问src var以获取所选图像的ID。使用Ajax进行了尝试,我们尝试将url传递给在控制器中创建的var,但是以某种方式ajax调用不起作用,因此controller var总是显示nil值。 we have tried ajax by 2 method: 我们通过两种方法尝试了ajax:

1: 1:

$('#submit').click(function(){
$.ajax({

    type: "POST",

    url: "index",

    cache: false,

    data: "src="+src1,

    success: function(){ 

           alert("DATA SAVED");

     }
});

2: 2:

<%= link_to_remote "submit" , :url=>{:controller=>'album',:action =>'index' ,:var=>'src1'}%>

i would suggest you to modify your Ajax to something like this. 我建议您将Ajax修改为类似的内容。

var MyTestData = '';
function ajax() {
    return $.ajax({
        url: 'index',
        type: 'POST',
        // make sure you use params[:src] in your controller method to access src1
        data: { src: src1 },
        // You should return your response in JSON format
        success: function(data){ MyTestData = data }
    });
}

So now the response which you get from your POST call will be saved in MyTestData variable. 因此,现在您从POST调用中获得的响应将保存在MyTestData变量中。
Example on how to send json response from a controller method 有关如何从控制器方法发送json响应的示例

def index
    # Use the data you passed in the Ajax call
    data = params[:src]
    # Do some processing
    result = something
    # Return the response in json
    render :json => result
end

Here is how you can use the ajax() function on submit event 这是在提交事件时可以使用ajax()函数的方法

$('#submit').click(function(){
    ajax().done(function() {
        // Your MyTestData variable will have whatever details your returned
        // on your POST call. you can test it by logging it in console
        console.log(MyTestData)
      }).fail(function(){
          alert('Ajax call Failed')
    });
});

Make sure your src1 variable is in scope. 确保您的src1变量在范围内。 The easiest way—though not the best—would be to just make src global, defined right inside your script tag. 最简单的方法(尽管不是最好的方法)将是使src全局化,就在您的脚本标签内部进行了定义。

Of course global variables are frowned upon, for good reason, so once this works look at tidying up the code and getting src declared more locally, or at least namespaced. 当然,有充分的理由不赞成使用全局变量,因此,一旦这项工作奏效,便会着眼于整理代码并在本地或至少命名空间中声明src。

Also, is the variable named src , or src1 ? 另外,变量名为src还是src1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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