[英]How to use Javascript and AJAX to render popup on index page Ruby on Rails 5
我有一個為班級項目開發的簡單庫存系統應用程序。 要求之一是在應用程序中使用某種形式的Javascript和AJAX做某事。 它不一定要大或超級復雜,但必須存在。 我的小組決定要做的是渲染一個彈出窗口,當您單擊“顯示”鏈接時,該彈出窗口顯示有關某項的信息,因為它類似於教授在課堂上所做的示例,並且對我們的應用程序也很有用。 但是我無法使其工作,它只是繞過了ajax和javascript的內容,直接進入了show.html.haml頁面。 這是我的代碼:
%p#notice= notice
%h1 Items
%table
%thead
%tr
%th Name
%th Description
%th Quality
%th Price
%th Location
%th Options
%tbody
- @items.each do |item|
%tr
%td= item.name
%td= item.description
%td
= item.quality
%br/
%br/
= item.quality_desc
%td= item.price
%td= item.location
%td{:colspan => "3"}
= link_to 'Show', item, class: "items"
= link_to 'Edit', edit_item_path(item)
= link_to 'Destroy', item, method: :delete, data: { confirm: 'Are you sure?' }
%br/
= link_to 'New Item', new_item_path
這是彈出窗口應該顯示的信息
%h1 Items
%h2
= item.name
, #{item.category}
%br/
- item.images.each do |image|
= image_tag(image.small.url)
%br
Price: $#{item.price}
%br/
Description: #{item.description}
%br/
Quality: #{item.quality},
\#{item.quality_desc}
%br/
Location: #{item.location}
%br/
%br/
%br/
= link_to 'Edit', edit_item_path(@item)
= link_to 'Close', '', id: 'closeLink'
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
# GET /items
# GET /items.json
def index
@items = Item.all
end
# GET /items/1
# GET /items/1.json
def show
render(:partial => 'item', :object => @item) if request.xhr?
end
# GET /items/new
def new
@item = Item.new
end
# GET /items/1/edit
def edit
end
# POST /items
# POST /items.json
def create
@item = Item.new(item_params)
respond_to do |format|
if @item.save
format.html { redirect_to @item, notice: 'Item was successfully created.' }
format.json { render :show, status: :created, location: @item }
else
format.html { render :new }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /items/1
# PATCH/PUT /items/1.json
def update
respond_to do |format|
if @item.update(item_params)
format.html { redirect_to @item, notice: 'Item was successfully updated.' }
format.json { render :show, status: :ok, location: @item }
else
format.html { render :edit }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /items/1
# DELETE /items/1.json
def destroy
@item.destroy
respond_to do |format|
format.html { redirect_to items_url, notice: 'Item was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_item
@item = Item.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def item_params
params.fetch(:item, {}).permit(:name, :description, :quality, :quality_desc, :price, :location, :category, { images: [] })
end
end
var ItemPopup = {
setup: function() {
// add hidden 'div' to end of page to display popup:
var popupDiv = $('<div id="itemInfo"></div>');
popupDiv.hide().appendTo($('body'));
$(document).on('click', '#items a', ItemPopup.getItemInfo);
},
getItemInfo: function() {
$.ajax({type: 'GET',
url: $(this).attr('href'),
timeout: 5000,
success: ItemPopup.showItemInfo,
error: function(xhrObj, textStatus, exception) {alert('Error!'); }
//'success' and 'error' functions will be passed 3 args
});
return(false);
},
showItemInfo: function(data, requestStatus, xhrObject) {
//center a floater 1/2 as wide and 1/4 as tall as screen
var oneFourth = Math.ceil($(window).width() / 4);
$('#itemInfo').css({'left': oneFourth, 'width': 2*oneFourth, 'top': 250}).html(data).show();
//make the Close link in the hidden element work
$('#closeLink').click(ItemPopup.hideItemInfo);
return(false); //prevent default link action
},
hideItemInfo: function() {
$('#itemInfo').hide();
return(false);
}
};
$(ItemPopup.setup);
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
// require turbolinks
// require_tree .
//= require items
!!!
%html
%head
%meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
%title InventoryManager
= csrf_meta_tags
// = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
// = javascript_include_tag 'application', 'data-turbolinks-track': 'reload'
= stylesheet_link_tag 'application'
= javascript_include_tag "application"
%body
%nav.navbar.navbar-default
.container-fluid
/ Brand and toggle get grouped for better mobile display
.navbar-header
%button.navbar-toggle.collapsed{"aria-expanded" => "false", "data-target" => "#bs-example-navbar-collapse-1", "data-toggle" => "collapse", :type => "button"}
%span.sr-only Toggle navigation
%span.icon-bar
%span.icon-bar
%span.icon-bar
%a.navbar-brand{:href => "/default/index"} InventoryManager
/ Collect the nav links, forms, and other content for toggling
#bs-example-navbar-collapse-1.collapse.navbar-collapse
%ul.nav.navbar-nav
%li.active
%a{:href => "#"}
Items
%span.sr-only (current)
%ul.nav.navbar-nav.navbar-right
- if admin_signed_in?
%li= link_to "Logout", destroy_admin_session_path, :method => :delete
- elsif employee_signed_in?
%li= link_to "Logout", destroy_employee_session_path, :method => :delete
- else
%li
%a{:href => "/admins/sign_in"} Admin
%li
%a{:href => "/employees/sign_in"} Staff
/ /.navbar-collapse
/ /.container-fluid
= yield
如果您需要更多的代碼,請詢問。 這是在Ruby on Rails 5中
編輯:所以我通過更改事件處理程序函數中的選擇器來修復它,使其讀為'#items',並且它使用該ID捕獲了我頁面上的元素。 但是,我從教科書中獲得了最初嘗試使用的代碼,這意味着應該執行的工作。 有人可以向我解釋為什么最初不起作用嗎?
EDIT2:沒關系,我想通了。
原來我的麻煩是這條線在這里:
$(document).on('click', '#items a', ItemPopup.getItemInfo);
我從班級的教科書中獲得了這段代碼,並對其進行了少許修改以適合我的應用程序。 因此,由於缺乏對選擇器工作原理的了解,我認為這是在選擇ID為“ items”的錨標簽。 事實證明,它實際上是在將所有錨標簽放入一個id為“ items”的元素中,對於本書而言,該特定元素是一個表,該表中的唯一鏈接轉到了該應用程序的show.html.haml頁面。 這對我的應用程序不太有效,因為索引表上有3種不同類型的鏈接,因此我將行更改為讀取
$(document).on('click', '.items', ItemPopup.getItemInfo);
並將我的index.html.haml上的“顯示”鏈接更改為具有“項目”類。 這解決了我的問題,現在可以正常使用。
話雖這么說,如果有解決此類問題的方法被認為是一種更好的做法,請隨時與我們分享,作為對這一問題的答案,我也全都在學習新知識。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.