2017-06-19 43 views
0

我早些時候有一些troubles with a JavaScript請求,並提供的解決方案似乎已經解決了問題(因爲我得到的不是從瀏覽器的控制檯錯誤),但我的應用程序不顯示的東西UI。 這裏是如何的請求正在由服務器處理:AJAX Rails - 請求顯然丟失 - 沒有UI結果

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) 

這裏是我的UI(它是一個局部的):

<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):在我的控制器,取消了「渲染JSON:@stock」:

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(); 
}) 

行,所以,基於的是,如果我評論了「‘查找’呈現局部」一個和處理請求通過我的瀏覽器直接:我得到我正在尋找的信息。這意味着寶石和請求正常工作。 一旦我試圖通過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 

下面是我的回購鏈接:https://github.com/Ardzii/finance-tracker

回答

1

您使用remote: true,你應該使用方法respond_to處理Ajax。這是一個例子,你可以一步做一步:

  1. 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 
    
  2. 刪除app/assets/javascripts/stocks.js

  3. 編輯操作search編輯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> 
    
  4. 創建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 %> 
    
  5. 創建app/views/stocks/search.js.erb

    $("#stock-lookup-results").html("<%= j render 'stock', {stock: @stock} %>"); 
    

完成!

+0

Hieu救援!非常感謝您的幫助和時間!我只是想知道,爲什麼你會在這種情況下使用迴應?我的意思是我明白你告訴應用程序使用html或js取決於客戶的請求,但不是總是js?然後我不確定我是否得到了部分的機制。如果我沒有弄錯,你不是在任何地方參考_stock ... – Ardzii

+0

如果你有一個很好的和推薦的tuto或課程來了解更多,我會很感激,如果你能分享它! :P – Ardzii

+1

Hi @Ardzii!首先,如果只想渲染js,只需刪除一行''格式。在'stocks_controller.rb'中的html'。其次,我在'app/views/stocks/search.js.erb'中渲染'_stock.html.erb'。 –