前提・実現したいこと
クリックイベントでモーダルを表示し、productsテーブルからランダムにレコードを1つ取得し、product_titleと画像を表示させたい。
クリックイベントのたびにランダムにproductを1つ取得し表示させるので、ajax側でproduct_idを取得し、attrでurlを結合させ、表示させたいのですが、idの取得方法がわかりません
初めての質問で不足があると思いますがお願いします
該当のソースコード
js
1$(function(){ 2 $(document).on('click', '#rock,#pop,#punk', function(){ 3 $.ajax({ 4 type:'GET', 5 url:'/api/json_top', 6 dataType: 'json', 7 }) 8 .done(function(data){ 9 console.log(data.name); 10 console.log(data.image); 11 12 $('#content-title,#content-image').empty(); 13 $('#overlay,#result').fadeIn(); 14 $('#content-title a').attr('href', '/products/' + 'data.name'); 15 $('#content-image img').attr("src", '' + 'data.image'); 16 17 $(document).on('click', '#overlay,#close', function(){ 18 $('#content').empty(); 19 $('#overlay,#result').fadeOut(); 20 $(document).on('click', '#result', function(e){ 21 e.stopPropagation(); 22 }); 23 }); 24 }) 25 26 .fail(function(){ 27 alert('fail') 28 }); 29 }); 30 });
ruby
1json.set! @random_product do |product| 2 json.name product.product_id 3 json.image product.image_id 4end
ruby
1class Api::RootsController < ApplicationController 2 def top 3 @random_product = Product.order("RANDOM()").first 4 render :json => { 5 name: @random_product.product_id, 6 image: @random_product.image_id 7 } 8 end 9end
回答1件
あなたの回答
tips
プレビュー