【问题标题】:Ajax call when clicking on a button in rails单击rails中的按钮时的Ajax调用
【发布时间】:2013-11-11 16:00:12
【问题描述】:

我基本上想在单击按钮时创建警报,而不是重新加载整个页面。

在我看来:

:javascript
  function ajax_test1(field)
  {
      var xmlhttp;
      if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
      }
      else
      {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }

      xmlhttp.open("GET", "test_ajax.xml?code=" + field.value, false);
      xmlhttp.send();
      xmlDoc=xmlhttp.responseXML;
      alert(xmlDoc.getElementsByTagName("message")[0].childNodes[0]);
  }

= button_to 'test ajax', :remote => true, :onclick => "ajax_test1(this);"

进入我的控制器

  def test_ajax
    @test = {message:'Hello there!'}
    render :xml => @test
  end

当我点击按钮时,页面正在重新加载,并带有以下 URL:

http://localhost:4242/test?onclick=ajax_test1%28this%29%3B&remote=true

请问我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails ajax haml


    【解决方案1】:

    onclick 事件需要返回 false 以阻止默认行为(实际点击)发生。

    如果您使用的是 jQuery,.preventDefault() 方法是防止默认事件行为的更好方法 - 但使用您的手卷 javascript,您将不得不有点混乱:

    = button_to 'test ajax', :remote => true, :onclick => "ajax_test1(this); return false;"
    

    【讨论】:

    • 我添加了return false;,但得到了相同的结果
    【解决方案2】:

    我改变了这个:

    = button_to 'test ajax', :remote => true, :onclick => "ajax_test1(this);"
    

    进入这个:

     = button_to_function 'test ajax', 'ajax_test1(this)'
    

    它成功了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-21
      • 2019-12-28
      • 2012-03-29
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      相关资源
      最近更新 更多