我对 Ruby 总体上是新手(对 jQ 和 Ajax 也是如此),但我总是在发帖前尝试阅读。
我无法使用 Ajax 将简单的 jQuery 变量发送到 Ruby Controller (为了平滑过渡)。
AJAX 可以将简单的变量传递给 ruby Controller 吗?
有必要吗,还有PHP、ASP.NET等脚本语言的帮助吗??
还有其他更简单的方法吗?
controller.rb
def show_NuevaVista
app_info(@params['myparam'])
@show_text = @params['myparam']
render :action => :test, :back => '/app' #test is a view that shows the global var show_text
end
view.rb
<button id="botonTweet" >More Tweets</button>
<script type="text/javascript">
$(document).ready(function(){
$('#botonTweet').click(function(slice) {
var stub = 1; //variable to be sent
$.ajax({
type: "POST",
url: "show_NuevaVista", //method of the controller
data: {
"test": stub //try to send this variable
},
});
});
});
</script>
更新:
我发送变量的唯一方法是使用 href 并且该变量是在 ruby 中声明的。
<%= @texto = "LOL!" %>
<%= link_to "Click Here!", :action => :show_NuevaVista,:query => {:myparam => @texto} %>
最佳答案
你对 link_to 和 jQuery 进行编码的方式,在 ajax 调用之后它仍然会执行 href。您可以执行以下操作:
<%= link_to("Click Here", "javascript:void(0);", :id => "botonTweet") %>
或者,如果您希望 href 执行作为回退,请使用相同的 link_to 代码并更新您的 javascript 以在 ajax 调用后返回 false :
$('#botonTweet').click(function(slice) {
var stub = 1; //variable to be sent
$.ajax({
type: "POST",
url: "show_NuevaVista", //method of the controller
data: {
"test": stub //try to send this variable
},
});
//this is the key to avoid href redirect
return false;
});
关于jquery - 使用 jQ 和 Ajax 将一个简单的变量传递给 Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7392751/