简体   繁体   English

Ror4 Ajax在页面加载时执行JavaScript

[英]Ror4 Ajax executing javascript on page load

I'm having a problem with the unobtrusive javascript in my application. 我在我的应用程序中使用兼容的JavaScript时遇到了问题。 I put an alert into the js.erb file to help me debug, but it runs whenever I load my page, and does nothing when I click the button. 我将警报放入js.erb文件中以帮助调试,但是该警报在加载页面时运行,并且在单击按钮时不执行任何操作。 I'm not really sure what I'm doing wrong. 我不太确定自己在做什么错。

users_controller.rb users_controller.rb

class UsersController < ApplicationController

def new
    @user = User.new
end

def create
    @user = User.new(user_params)

    respond_to do |format|
        if @user.save
            format.html { redirect_to :root, notice: 'User was successfully created.' }
            format.js   { render :text => "FINISHED THE AJAX REQUEST" }
        else
            format.html { render action: "new" }
            format.js   {}
        end
    end
end

def edit
    @user = User.find(params[:id])
end

def index
    @user  = User.find(params[:id])
end

private

    def user_params
  params.require(:user).permit(:email)
end

end

create.js.erb create.js.erb

alert("BUTTON CLICKED");
$('.button').text("Thank You!");
$('.button').animate({"background-color":"#088A08"},300);
$('#e_submit').css("box-shadow","0 0 0px rgba(0, 0, 0, 0)");
$('#e_submit').val("");

welcome.html.erb welcome.html.erb

<%= form_for(User.new, remote: true) do |f| %>
<%= f.text_field :email, class: "e_submit", placeholder:"Enter your email" %>               
<%= f.submit "Subscribe", class: "button" %>
<% end %>

I can't figure out why @user instead of User.new doesn't work, but that's a question for a different day. 我不知道为什么@user而不是User.new无法正常工作,但这是另一个问题。

Ok I figured it out. 好吧,我知道了。 This all stemmed from my misunderstanding of javascript and where it goes in a rails 4 application. 这一切都源于我对javascript的误解以及它在Rails 4应用程序中的位置。 I put it in app/assets/javascripts/ when I should have put it in app/views/users along with the view HTML files. 我将它与视图HTML文件一起放在app / views / users中时,将其放在app / assets / javascripts /中。

When I put it in that directory, it no longer needed any of the ready function stuff. 当我将其放在该目录中时,它不再需要任何可用的函数。 Also, I had to remove format.js {} with just format.js. 另外,我必须仅用format.js删除format.js {}。 This is now working. 现在正在工作。 Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM