【发布时间】:2021-05-28 15:48:11
【问题描述】:
应用程序.js
require("@rails/ujs").start()
require("turbolinks").start();
require("@rails/activestorage").start();
require("channels");
require("bootstrap");
require("jquery");
require('popper.js');
require("channels/jquery.nice-select.min.js");
require("channels/owl.carousel.min.js");
require("@fortawesome/fontawesome-free");
contacts_controller.rb
class ContactsController < ApplicationController
def index
@contact = Contact.new
end
def create
@contact = Contact.new(contact_params)
respond_to do |format|
if @contact.save
ContactMailer.with(contact: @contact).notification.deliver_now
format.html {redirect_to contacts_path}
format.js { }
else
format.html {render :index}
format.json {render json: @contact.errors, status: :unprocessable_entity}
end
end
end
private ##
def contact_params
params.require(:contact).permit(:name, :phone_number, :message, :email)
end
end
因为我想尝试看看 format.js 是否会运行,所以它只有 1 行
create.js.erb
console.log('sending alert!');
index.html.haml
.main_contact_inner
= form_for @contact , url: contacts_path do |f|
- if @contact.errors.any?
%ul
- @contact.errors.full_messages.each do |msg|
%li= msg
#contactForm.row.contact_form
.form-group.col-md-4
= f.text_field :name, class: 'form-control', placeholder: 'Tên'
.form-group.col-md-4
= f.text_field :phone_number, class: 'form-control', placeholder: 'Số Điện Thoại'
.form-group.col-md-4
= f.text_field :email, class: 'form-control', placeholder: 'Email'
.form-group.col-md-12
= f.text_area :message, class: 'form-control', placeholder: 'Tin nhắn', rows: 1
.form-group.col-md-12
%button.btn.submit_btn.red.form-control{:type => "submit", :value => "submit"} Gửi đi
创建联系人后,控制台不显示任何日志。
我不知道为什么我的代码不能进入 format.js,谁能帮我解决这个问题?
或者有人可以告诉我如何在不使用控制器的情况下创建像 sweetalert2 这样的警报。
【问题讨论】:
-
您好,您来对了地方寻求帮助,您的问题已经很好地为别人提供了帮助。您能否向我们展示您调用 Ajax 操作的客户端代码是什么样的?另外,您能否向我们展示更多的 create.js.erb 而不仅仅是那一行?现在很难回答这个问题,但这些信息可能会有所帮助。
-
@RyanPorter 我想检查 format.js 是否正常工作,所以只需在 create.js.erb 中的 1 行,但它不工作。
-
哇好棒。代码中的泰语字符。我以前从未见过。我没有看到您从客户端 HTML 调用 Ajax 操作的位置?我怀疑您没有看到控制台输出是因为您的前端代码没有调用 XHR 操作?
-
@RyanPorteri 认为,只是为了 format.js 会自动调用文件 create.js.erb,你能告诉我正确的吗?
-
我认为 Joel 的回答解释了为什么您的前端代码没有调用您的 XHR 操作。
标签: javascript ruby ajax ruby-on-rails-6