如何设置一个等于javascript变量的rails变量

如何设置一个等于javascript变量的rails变量

本文介绍了如何设置一个等于javascript变量的rails变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做类似于但我似乎无法让它适用于我的目的。我正在使用拖放jQuery将项目转移到pods。这是我的代码:

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 %>
}

但我知道解决方案并不那么容易。如何将id和pod_id传递给我的控制器?理想情况下,我想将其传递给更新操作。 PS:我根本不认识AJAX,所以如果这是唯一的方式请提供详细信息...

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...

推荐答案

唯一将数据从浏览器客户端传递到rails应用程序的方法是通过HTTP。要在JavaScript中执行HTTP,您可以使用XHR(也称为AJAX)。您不能像在代码示例中建议的那样在模板中执行此操作,因为模板由服务器上的Rails呈现,并在客户端上作为HTML和JavaScript进行评估。客户端/浏览器和服务器之间没有内联通信。

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.

假设jQuery:

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

然后你需要设置一个控制器来响应/ some / url,并且做任何你需要做的事情 params [:pod_id] params [: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].

这篇关于如何设置一个等于javascript变量的rails变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:14