2015-10-18 148 views
0

我的rails應用程序在ajax請求之後有很多客戶端javascript回調,但是我一直無法通過route> controller> erb文件獲得正確的流程來工作。Ajax請求不返回erb文件

這裏是一個例子,開始與AJAX請求:

$(initElement).on("click", function(){ 
     event.preventDefault(); 
     var url = "http://localhost:3000/login"; 

     $.ajax({ 
      url: url, 
      method: "GET", 
      dataType: "html" 
     }).done(function(){ 
      console.log("*** ajax success T ***"); 
      displayObject.toggleSelectionLabels("show"); 
     }).fail(function(){ 
      console.log("*** ajax fail T ***"); 
     }); 
    }); 

在routes.rb中

get "/login" => "sessions#login" 

的會話控制器登錄動作路線:

def login 
    puts "******* login " + "*" * 21 
end 

登錄.html.erb文件我期待從服務器:

<% @page_title = "UserAuth | Login" %> 

<div class="form-column login"> 
    <h1>Log in</h1> 
    <div class="tag-edits photo-form"> 
     <%= form_tag(:action => 'login_attempt') do %> 
     ... edited out... 
     <% end %> 
    </div> 
</div> 

ajax請求獲取路由,作爲「成功」返回並且toggleSelectionLabels回調運行,但不會顯示erb內容。 ajax是否阻止了rails中的正常處理?

回答

0

正常處理是什麼意思?如果你想顯示返回的HTML,你可能想要做這樣的事情

$(initElement).on("click", function(){ 
    event.preventDefault(); 
    var url = "http://localhost:3000/login"; 

    $.ajax({ 
     url: url, 
     method: "GET", 
     dataType: "html" 
    }).success(function(response) { 
     // response is your html, use it to inject it into the html 
     // for Example 
     $('.main-div').html(response); 
    }).done(function(){ 
     console.log("*** ajax success T ***"); 
     displayObject.toggleSelectionLabels("show"); 
    }).fail(function(){ 
     console.log("*** ajax fail T ***"); 
    }); 
}); 

注意success回調。當服務器的響應有一個httpStatus = 200(確定)

+0

感謝您的幫助。我現在得到了erb的內容,但是它包含了整個佈局文件(而不僅僅是erb內容,我希望它自己填充<% yield %>)。換句話說,整個頁面會重新加載並填充收益。這個警告也是:「主線程上的同步XMLHttpRequest已被棄用......」就好像我正在發送2個請求。有什麼想法嗎? – tomBeach

+0

要刪除佈局,只需將'render layout:false'作爲控制器'login'方法的最後一行添加即可。至於警告,看看這個其他SO [post](http://stackoverflow.com/questions/24639335/javascript-console-log-causes-error-synchronous-xmlhttprequest-on-the-main-thr) 。一旦你準備好了,不要忘記將答案標記爲已接受。 – nbermudezs