AJAX Rails-请求明显丢失-没有UI结果 [英] AJAX Rails - Request apparently lost - No UI Results

查看:60
本文介绍了AJAX Rails-请求明显丢失-没有UI结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些使用JavaScript的问题较早地请求,并且提供的解决方案似乎已解决了该问题(因为我没有从浏览器的控制台中收到错误),但是我的应用未在用户界面中显示任何内容. 服务器如何处理请求:

I had some troubles with a JavaScript request earlier and the solution provided seems to have fixed the problem (since I get not error from the browser's console) however my app doesn't display a thing in the UI. Here's how the request is being handled by the server:

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)

这是我的用户界面(部分):

Here's my UI (it's a partial):

<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):

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

好的,基于此,如果我在控制器中评论"render局部:'lookup'",请取消注释"render json:@stock",然后直接通过浏览器处理请求:我得到了信息在寻找.这意味着gem和请求正在正常工作. 一旦我尝试通过AJAX处理请求,我什么也没得到……有人有解决方案吗?我感到自己对JavaScript的处理不佳,或者可能缺少宝石或其他东西. 无论如何,这是我的gem文件供参考:

OK so, based on that, if I comment the "render partial: 'lookup'" in my controller, uncomment the "render json: @stock" one and handle the request via my browser directly: I get the info I'm looking for. Meaning that the gem and the request are working correctly. Once I'm trying to handle the request via AJAX I get nothing... Anybody have a solution? I get the feeling that I'm handling the JavaScript poorly or that maybe I'm missing a gem or something. Anyhow, for reference here's my gem file:

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

And here's a link to my repo: https://github.com/Ardzii/finance-tracker

推荐答案

您正在使用remote: true,应该使用方法respond_to来处理ajax.这是一个示例,您可以逐步进行:

You're using remote: true, you should to use method respond_to to handle ajax. This is an example, you can do step by step:

  1. 删除app/assets/javascripts/stocks.js
  2. 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} %>");
    

  • 完成!!!

    这篇关于AJAX Rails-请求明显丢失-没有UI结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆