2013-10-31 33 views
1

我基本上想在點擊一個按鈕時創建一個警報,並重新加載整個頁面。點擊軌道上的按鈕時Ajax調用

進入我的觀點:

: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 

當我點擊該按鈕時,頁面與下面的網址重裝:

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

我該如何解決這個問題?

回答

0

我改變了這種:

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

到這一點:

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

,它的工作ED!

1

onclick事件需要返回false以停止默認行爲 - 實際點擊 - 發生。

如果你使用jQuery,該.preventDefault()方法是防止違約事件行爲的一種更好的方式 - 但你的手挽的JavaScript你必須有點凌亂:

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

我添加了'return false;'但得到了相同的結果 – Pol0nium