如何在jQuery中获取结果页面

时间:2019-02-22 14:16:44

标签: ajax rubygems ruby-on-rails-5 contactus jquery-rails

在controller:create和errorpage呈现到“ new”页面之后,成功页面被重定向到同一页面。因此,我希望在同一页面本身中出现此错误页面。那么如何在jquery ajax中获取结果页面呢?以及如何解决给定的jQuery代码以获取结果页面?

projectdir
  -app
   -views
    -contact-us
         -contact_mailer
            #somefiles
         -contacts
             new.html.erb

new.html.erb

<%= form_for @contact, :url => contacts_path, :html => {:class => 
'formtastic'}, remote: true, id: "contactform" do |f| %>

 <% if ContactUs.require_name %>
    <div class='string required' id='contact_us_contact_name_input'>
      <%= f.label :name, (t('.name') + content_tag(:abbr, '*', :class => 
         'required')).html_safe %>
      <%= f.text_field :name %>
      <% if f.object.errors[:name].present? %>
        <p class='inline-error'><%= f.object.errors[:name].join(' and ') %> 
        </p>
       <% end %>
    </div>
 <% end %>  

# --- remaining lines for email,message

<div class='commit'>
<%= f.submit :submit, :class => 'submit 
    create', :title => t('.submit'), :value => t('.submit') %>
 </div>

<div class="content">
  <% flash.each do |key, msg| %>
    <%= content_tag :div, msg, :class => [key, " message"], :id => "notice_#{key}" %>
  <% end %>
</div>
  

gem的controller / contact_us / contacts_controller.rb内置方法创建

class ContactUs::ContactsController < ApplicationController
 def create
 @contact = ContactUs::Contact.new(params[:contact_us_contact])

if @contact.save
  redirect_to(ContactUs.success_redirect || '/', :notice => t('contact_us.notices.success'))
else
  flash[:error] = t('contact_us.notices.error')
  render new
end
end

application.js

$('#contactform').submit (e) ->
e.preventDefault()
console.log "submitted form."

$.ajax
  url: '/contacts'
  type: 'POST'  
  data:
    name: $(this).find("input[name='name']").val()
    email: $(this).find("input[name='email']").val()
    message: $(this).find("textarea[name='message']").val()
  success: (result) ->
    $("#contactform").html(result);
  error: (result) ->
    alert("couldn't send your message.") 

0 个答案:

没有答案