【问题标题】:Pass a simple variable using jQ & Ajax to Ruby使用 jQ 和 Ajax 将简单变量传递给 Ruby
【发布时间】:2011-11-15 14:30:38
【问题描述】:

我对 Ruby 很陌生(对 jQ 和 Ajax 也是如此),但我总是在发帖前尝试阅读。

我无法使用 Ajax 将简单的 jQuery 变量发送到 Ruby 控制器(以实现平滑过渡)。

可以通过 AJAX 将简单变量传递给 ruby​​ 控制器吗?

有必要,还有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} %> 

【问题讨论】:

  • 我这样做的不寻常方式是使用以下代码: :show_NuevaVista,:query => {: myparam => @texto} %>
  • 这条线是干什么用的?数据未定义。 for(var i=0; i
  • 抱歉,我删除了一些额外的代码,但现在已修复。

标签: jquery ruby ajax variables


【解决方案1】:

你有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;
});

【讨论】:

    猜你喜欢
    • 2017-02-22
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 2011-09-02
    • 1970-01-01
    相关资源
    最近更新 更多