1

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

在我看来:

: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

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

4

2 回答 2

1

onclick 事件需要返回false以停止默认行为——实际点击——的发生。

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

= button_to 'test ajax', :remote => true, :onclick => "ajax_test1(this); return false;"
于 2013-10-31T15:09:32.267 回答
0

我改变了这个:

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

进入这个:

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

它奏效了!

于 2013-10-31T15:22:23.987 回答