【发布时间】:2018-08-03 12:56:50
【问题描述】:
我使用stock gem 搜索公司名称并返回last-price。添加Ajax 时不返回任何内容。控制台没有错误,但是当打开网络时出现消息 failed to load data 。
stock_controller.rb
def search
if params[:stock].present?
@stock = Stock.new_form_lookup(params[:stock])
if @stack
respond_to do |format|
format.js { render partial: 'users/result' }
end
else
flash[:danger] = "You have entered an incorrect symbol"
redirect_to my_portfolio_path
end
else
flash[:danger] = "You have entered an empty search string"
redirect_to my_portfolio_path
end
end
my_portfolio.html.erb
<h1>My Portfolio</h1>
<h3>Search for Stocks</h3>
<div id="stock-lookup">
<%= 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="fa fa-search"></i> Look up a stock
<% end %>
</div>
</div>
<% end %>
</div>
<div id="results">
<%= render 'result' %>
</div>
_result.html.erb
<% if @stock%>
<div class="well result-block">
<strong>Symbol:</strong> <%= @stock.ticker%>
<strong>Name:</strong> <%= @stock.name%>
<strong>Price:</strong> <%= @stock.last_price%>
</div>
<%end%>
_result.js.erb
$("#results").html("<%= j(render 'users/result.html') %>");
当测试文件_result.js.erb 添加alert("hello"); 工作正常。
添加ajax的设置
- 在表单中添加远程:true
- 在 application.js 中添加 JQuery
- 使用 format.js 和部分:
- 创建文件_result.js.erb
stock model
def self.new_form_lookup(ticker_symbol)
begin
looked_up_stock = StockQuote::Stock.quote(ticker_symbol)
#price = strip_commas(looked_up_stock.latest_price)
new(name: looked_up_stock.company_name,
ticker: looked_up_stock.symbol, last_price: looked_up_stock.latest_price)
rescue Exception => e
return nil
end
end
输出日志
【问题讨论】:
-
@stack在哪里实例化? -
查看您的日志而不是浏览器控制台。那会更有帮助。
-
@FabrizioBertoglio 添加库存型号请查看
-
@Leo 这个出现`参数:{"utf8"=>"✓", "stock"=>"GOOG", "button"=>""}`
-
你在哪里实例化
@stack?
标签: ruby-on-rails ruby ajax