ajax不适用于rails 5



i使用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') %>");

当测试文件CCD_ 8和CCD_。

添加ajax 的setp

  • 在表单中添加remote:true
  • 在application.js中添加JQuery
  • 使用format.js和partial:
  • 创建文件_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

如果@stack不是nil,则仅respondjs

@stack的值是多少?它从哪里得到这个值?

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

最新更新