Ajax call when clicking on a button in rails

2019-07-27 02:27发布

I basically want to create an alert when clicking on a button, withour reloading the entire page.

Into my view :

: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]);
  }

and

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

Into my controller

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

When I click on the button, the page is reloading with the following URL:

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

How can I fix this please?

2条回答
劳资没心,怎么记你
2楼-- · 2019-07-27 02:37

I changed this :

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

into this:

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

and it worked!

查看更多
虎瘦雄心在
3楼-- · 2019-07-27 02:43

The onclick event needs to return false in order to halt the default behaviour – the actual click – from taking place.

If you were using jQuery, the .preventDefault() method is a nicer way of preventing the default event behaviour – but with your hand rolled javascript you'll have to be a bit messier:

= button_to 'test ajax', :remote => true, :onclick => "ajax_test1(this); return false;"
查看更多
登录 后发表回答