我試圖用兩列創建一個簡單的頁面。在左欄中,用戶可以填寫表格。在表單提交中,我想要右列刷新(通過AJAX)並使用已在控制器中創建的@url字符串填充div。現在,表單提交併不會激發我的.js頁面上的代碼 - 相反,它會重定向遠離頁面,並將我的.js作爲純文本加載到瀏覽器中。這應該是如此簡單 - 我做錯了什麼?Rails 4在嘗試使用AJAX時以純文本的形式加載JS
在配置/路線:
root 'home#home'
post '/pixify', to: 'home#pixify', as: "pixify", format: 'js'
在HomeController的:
class HomeController < ApplicationController
respond_to :html, :js
skip_before_action :verify_authenticity_token
def home
end
def pixify
@url = "http://example-url.com"
respond_to do |format|
format.js { render :layout => false }
end
end
end
在意見的/ home/home.html.haml:
%div#container
%div.left-column
= form_tag pixify_path, :remote => true do
%fieldset
%ul
%li
%label{:for => "url-id"} URL ID:
%input{:type => "text", :name => "url-id"}
%input{:type => "submit", :value => "Generate url", :class => "button"}
%div.right-column
%div#generated-url
在視圖/家庭/ pixify .js.erb:
console.log("This is working"); // but it isn't
$('#generated-url').html('http://www.justanexample.com');
檢查表單的輸出HTML,它應該有'數據遠程=「真」',還需要包括與軌道一起提供的'jquery-ujs'腳本。 – alan0xd7
HTML輸出確實有data-remote =「true」,並且application.js中都需要'require jquery'和'require jquery_ujs'。還有其他建議嗎? – seesarahcode
@seesarahcode - 你可以嘗試從控制器中刪除'format:'js''選項,並且'render:layout => false'嗎? –