How to set a rails variable equal to a Javascript variable?
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 %>
&l开发者_如何转开发t;% @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...
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]
.
精彩评论