How to set a rails variable equal to a javascript variable?

走远了吗. 提交于 2020-01-01 03:52:27

问题


I want to do something similar to How to pass a Javascript variable to Rails Controller? but I can't seem to get it working for my purposes. I'm using drag and drop jQuery to transfer "items" to "pods". Here's my code:

function onReceive(id,pod_id){
var id = id;
var pod_id = pod_id;
confirm("Add " +id + " to " + pod_id + "?");
}

What I want to do is really something like this:

function onReceive(id,pod_id){
<% @pod_id = pod_id %>
<% @id = id %>
}

But I know that the solution isn't quite that easy. How can I pass id and pod_id to my controller? Ideally, I'd like to pass it to the update action. P.S.: I don't know AJAX at all, so if that's the only way please provide details...


回答1:


The only way to pass data from the browser client side to a rails app, is via HTTP. And to do HTTP in JavaScript, you use XHR (also called AJAX). You can't do it in the templates as you're suggesting in your code sample, since the template is rendered by Rails on the server, and evaulated as HTML and JavaScript on the client. There's no inline communication between the client/browser and the server.

Assuming jQuery:

function onReceive(id,pod_id){
    $.ajax({
        url: "/some/url",
        data: {pod_id: pod_id, id: id} 
    });
}

Then you need to set up a controller to respond to /some/url, and do whatever you need to do with params[:pod_id] and params[:id].



来源:https://stackoverflow.com/questions/6835512/how-to-set-a-rails-variable-equal-to-a-javascript-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!