我之前有一些troubles with a JavaScript请求,并且提供的解决方案似乎解决了问题(因为我没有从浏览器的控制台得到错误)但是我的应用程序没有显示任何内容用户界面。 以下是服务器处理请求的方式:
Started GET "/search_stocks?utf8=%E2%9C%93&stock=GOOG&button=" for 127.0.0.1 at 2017-06-19 12:50:13 +0200
Processing by StocksController#search as JS
Parameters: {"utf8"=>"✓", "stock"=>"GOOG", "button"=>""}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
Stock Load (0.4ms) SELECT "stocks".* FROM "stocks" WHERE "stocks"."ticker" = ? ORDER BY "stocks"."id" ASC LIMIT ? [["ticker", "GOOG"], ["LIMIT", 1]]
Rendered stocks/_lookup.html.erb (1084.6ms) [cache miss]
Completed 200 OK in 3002ms (Views: 1114.2ms | ActiveRecord: 0.8ms)
这是我的用户界面(它是部分的):
<div id="stock-lookup">
<h3>Search for stocks</h3>
<%= form_tag search_stocks_path, remote: true, method: :get, id: 'stock-lookup-form' do %>
<div class="form-group row no-padding text-center col-md-12">
<div class="col-md-10">
<%= text_field_tag :stock, params[:stock], placeholder: "Stock ticker symbol", autofocus: true, class: 'form-control search-box input-lg' %>
</div>
<div class="col-md-2">
<%= button_tag(type: :submit, class: "btn btn-lg btn-success") do %>
<i class="glyphicon glyphicon-search"></i> Look up a stock
<% end %>
</div>
</div>
<% end %>
<% if @stock %>
<div id='stock-lookup-results' class="well results-block">
<strong>Symbol:</strong> <%= @stock.ticker %>
<strong>Name:</strong> <%= @stock.name %>
<strong>Price:</strong> <%= @stock.price %>
</div>
<% end %>
</div>
以下是方法:
class Stock < ApplicationRecord
def self.find_by_ticker(ticker_symbol)
where(ticker: ticker_symbol).first
end
def self.new_from_lookup(ticker_symbol)
looked_up_stock = StockQuote::Stock.quote(ticker_symbol)
return nil unless looked_up_stock.name
new_stock = new(ticker: looked_up_stock.symbol, name: looked_up_stock.name)
new_stock.last_price = new_stock.price
new_stock
end
def price
closing_price = StockQuote::Stock.quote(ticker).close
return "#{closing_price} (Closing)" if closing_price
opening_price = StockQuote::Stock.quote(ticker).open
return "#{opening_price} (Opening)" if opening_price
'Unavailable'
end
end
控制器:
class StocksController < ApplicationController
def search
if params[:stock]
@stock = Stock.find_by_ticker(params[:stock])
@stock ||= Stock.new_from_lookup(params[:stock])
end
if @stock
#render json: @stock
render partial: 'lookup'
else
render status: :not_found, nothing: true
end
end
end
和JavaScript(AJAX):
var init_stock_lookup;
init_stock_lookup = function() {
$('#stock-lookup-form').on('ajax:success', function(event, data, status) {
$('#stock-lookup').replaceWith(data);
init_stock_lookup();
})
}
$(document).ready(function() {
init_stock_lookup();
})
好的,基于此,如果我评论&#34;渲染部分:&#39;查找&#39;&#34;在我的控制器中,取消注释&#34;渲染json:@ stock&#34;一,直接通过我的浏览器处理请求:我得到了我正在寻找的信息。意味着gem和请求正常工作。 一旦我试图通过AJAX处理请求,我什么都没得到......有人有解决方案吗?我觉得我很难处理JavaScript,或者我可能错过了一个宝石或其他东西。 无论如何,在这里参考我的宝石文件:
source 'https://rubygems.org'
git_source(:github) do |repo_name|
repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
"https://github.com/#{repo_name}.git"
end
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.1'
gem 'devise'
gem 'twitter-bootstrap-rails'
gem 'devise-bootstrap-views'
gem 'sprockets-rails', :require => 'sprockets/railtie'
gem 'jquery-rails'
gem 'jquery-turbolinks', '~> 2.1'
gem 'stock_quote'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
gem 'sqlite3'
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '~> 2.13'
gem 'selenium-webdriver'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
group :production do
gem 'pg'
gem 'rails_12factor'
end
答案 0 :(得分:1)
您正在使用remote: true
,您应该使用方法respond_to
来处理ajax。这是一个例子,你可以一步一步地做:
app/assets/javascripts/stocks.js
在search
app/controllers/stocks_controller.rb
def search
if params[:stock]
@stock = Stock.find_by_ticker(params[:stock])
@stock ||= Stock.new_from_lookup(params[:stock])
end
respond_to do |format|
format.html
format.js
end
end
修改app/views/stocks/_lookup.html.erb
<div id="stock-lookup">
<h3>Search for stocks</h3>
<%= form_tag search_stocks_path, remote: true, method: :get, id: 'stock-lookup-form' do %>
<div class="form-group row no-padding text-center col-md-12">
<div class="col-md-10">
<%= text_field_tag :stock, params[:stock], placeholder: "Stock ticker symbol", autofocus: true, class: 'form-control search-box input-lg' %>
</div>
<div class="col-md-2">
<%= button_tag(type: :submit, class: "btn btn-lg btn-success") do %>
<i class="glyphicon glyphicon-search"></i> Look up a stock
<% end %>
</div>
</div>
<% end %>
<div id='stock-lookup-results' class="results-block"></div>
</div>
创建app/views/stocks/_stock.html.erb
<% if stock.present? %>
<strong>Symbol:</strong> <%= stock.ticker %>
<strong>Name:</strong> <%= stock.name %>
<strong>Price:</strong> <%= stock.price %>
<% else %>
<i>Stock not found</i>
<% end %>
创建app/views/stocks/search.js.erb
$("#stock-lookup-results").html("<%= j render 'stock', {stock: @stock} %>");
完成!!!