我正在製作一個股票應用程序,基本上用戶需要輸入股票代碼,經過ajax調用後,它將返回包含價格,股票代碼和名稱的實例變量。它也將呈現在搜索欄的正下方。進行AJAX調用以從搜索表單結果中獲取數據以進行呈現。
這裏的PIC是模型
<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='fa fa-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>
<div id="stock-lookup-errors"></div>
<% end %>
</div>
這裏是控制器
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
puts @stock.price
render partial: 'lookup'
else
render status: :not_found, nothing: true
end
end
end
,當我把放@ stock.price,我獲取我想要的信息。然後它繼續渲染我想要的頁面,但它似乎不能讓我得到在erb文件中呈現的信息,並且if條件表示@stock,表示必要的信息。
這裏是給你一個我正在談論的想法的看法。
<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='fa fa-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>
<div id="stock-lookup-errors"></div>
<% end %>
</div>
我也正在一個單獨的js文件中做ajax調用,似乎正在做它的工作。
var init_stock_lookup;
init_stock_lookup = function() {
$('#stock-lookup-form').on('ajax:success', function(event, data, status) {
$('#stock-lookup').append(data);
init_stock_lookup();
})
}
$('#stock-lookupform').on('ajax:error',function(event, xhr, status, error){
$('#stock-lookup-results').replaceWith(' ');
$('#stock-lookup-errors').replaceWith('Stock was not found.')
});
$(document).ready(function(){
init_stock_lookup();
})
def不是鐵軌或紅寶石主,所以任何幫助將不勝感激!
@Зелёный我刪除了兩個答案,因爲它們都是錯誤的。對不起 –
ajax代碼是什麼?你正在使用'turbolinks'?你爲什麼使用'$(document).ready()'? –