我是使用jQuery的Rails和AJAX的新手。我的頁面有用戶選擇服務器的單選按鈕,根據這個選擇我的第一個下拉框'dir_list'填充了頂級目錄路徑,然後基於這個選擇第二個下拉框填充了用戶可以選擇的文件運行測試。無法讓AJAX或jQuery在rails4的動態選擇列表中工作
我有第一個使用單選按鈕的選擇框。我能夠在沒有AJAX的情況下做到這一點。 :onchange我調用了我的索引頁面中的JavaScript函數。它讀取值,執行一些if/else邏輯,然後使用JavaScript中的if/else邏輯硬編碼的正確本地呈現dir_list的局部頁面。我不能爲我的第二個選擇框做這個。它是動態的,它的價值必須通過AJAX傳遞。我一直在閱讀和嘗試幾天的例子,但我已經實現的AJAX和jQuery不起作用。我相信這些例子中有一些假設,我錯過了一些東西,因爲我對此很陌生。
我在Rails4中運行,所以我不能使用remote_function。我的application.js文件中有jQuery。
這裏是項目/ app/assets/javascripts/application.js文件:(我把所有jQuery/AJAX測試的例子代碼出來了,它回到了初始狀態)我應該可以做到這一點而不需要添加任何新寶石。
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
在這一點上,我開始使用form_tag並提交更改。它半工程,但因爲我有一個主表單url調用按鈕單擊我遇到問題。
第二個問題是如何插入文件的變量目錄路徑。我將爲這個問題打開另一個問題,並將這一問題集中在如何使用AJAX或jQuery上。我已經閱讀並嘗試了很多例子,所以有人請告訴我,我需要做的一步一步,以及我的具體案例的代碼示例文件的位置?
這是我的控制器代碼:索引加載。然後,當按下「驗證文件」按鈕並調用evaluate_media方法並加載回頁面時。 (這部分全部工作。)file_dir是我有表單提交以重新填充第二個選擇框調用的部分。
require 'media_info'
require 'alias_generator'
require 'rexml/document'
class FileAliasValidatesController < ApplicationController
def index
@state = 'index'
@file_alias_validate = FileAliasValidate.all
@file_exists_flag = "U" #U for Unknown or Undeterrmined.
@radio_button_value = 'miniprod'
@dir_path_choice = '/watchfolder/miniprod/hot'
end
def file_dir
@dir_path_choice = params[:dir_list]
render :partial => 'list_files', :locals => {:dir_path_choice => @dir_path_choice }
end
def evaluate_media
@state = 'post'
@radio_button_value = params[:location]
#Determine if file chosen has been saved to database yet.
@stored_file = FileAliasValidate.where(:full_path => params[:filepath], :deleted_b => 0).first
if @stored_file.present?
@file_exists_flag = 'Y'
@file_exists_msg = 'File Alias has been saved in application.'
else
@file_exists_flag = 'N'
@file_exists_msg = 'File Alias has NOT been saved in application yet.'
end
#Store selected value for re-display on post.
@selected_filepath = params[:filepath]
@filepath = File.join(params[:filepath])
@media_xml = ::MediaInfo.call(@filepath) #Filepath is sent in from the index html
@alias_xml = ::AliasGenerator.call(@media_xml)
@media_xml_for = ""
@alias_xml_for = ""
REXML::Document.new(@media_xml).write(@media_xml_for, 1)
REXML::Document.new(@alias_xml).write(@alias_xml_for, 1)
alias_parse_doc = ""
media_parse_doc = ""
alias_parse_doc = REXML::Document.new(@alias_xml)
media_parse_doc = REXML::Document.new(@media_xml)
#parse Alias XML Doc
@aliasgen_ver = REXML::XPath.each(alias_parse_doc, "/aliasGenerator vr=/text()") { |element| element }
@file_alias = REXML::XPath.each(alias_parse_doc, "*//alias/text()") { |element| element }
@file_status = REXML::XPath.each(alias_parse_doc, "*//error/text()") { |element| element }
@file_msg = REXML::XPath.each(alias_parse_doc, "*//error_m/text()") { |element| element }
@msg_dtl1 = REXML::XPath.each(alias_parse_doc, "*//closestvideoalias/text()") { |element| element }
@msg_dtl2 = REXML::XPath.each(alias_parse_doc, "*//closestaudioalias/text()") { |element| element }
#parse Video Media Info XML Doc
@filepathname = REXML::XPath.each(media_parse_doc, "*//Complete_name/text()") { |element| element }
@video_format = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Format/text()") { |element| element }
@video_bitrate = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Bit_rate/text()") { |element| element }
@video_width = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Width/text()") { |element| element }
@video_height = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Height/text()") { |element| element }
@video_aspectratio = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Display_aspect_ratio/text()") { |element| element }
@video_framerate = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Frame_rate/text()") { |element| element }
@video_scantype = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Scan_type/text()") { |element| element }
@video_scanorder = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Scan_order/text()") { |element| element }
render :action => :index
end
end
這裏是索引代碼:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Alias Validation -- Content Planner One Off Tool</title>
</head>
<h1>Alias File Validation</h1>
<p><%= link_to "Main Menu Page", mainpages_home_path %> <%= ', ' %> <%= link_to "Alias Home Page", alias_main_pages_home_path %> </p>
<%= form_tag file_alias_validates_evaluate_media_url do %>
<p>
<fieldset>
<legend>File Information:</legend>
<div class="form_row">
<label for="dir_location">Select File Location:</label>
<br><%= radio_button_tag 'location', 'miniprod', checked = true, :onclick => "render_dir_partial();" %> MiniProd Watch Folder
<%= radio_button_tag 'location', 'watch', checked = false, :onclick => "render_dir_partial();" %> Prod Watch Folder
<%= radio_button_tag 'location', 'archive', checked = false, :onclick => "render_dir_partial();" %> Prod Archive Folder
<%= radio_button_tag 'location', 'local', checked = false, :onclick => "render_dir_partial();" %> Local Test
</div> <br />
<%= form_tag({:controller => 'file_alias_validates', :action => 'file_dir', :method => :get}, {:id => 'dir_select_tag'}) do %>
<div id="dir_list">
<%= render :partial => 'dir_list', :locals => {:dir_choice => @radio_button_value } %>
</div><br />
<% end %>
<div id="list_files">
<label for="file_list">Select Test File:</label>
<label>Dir Selected Path Value: </label><%= @selected_dir_list %>
<%= render :partial => 'list_files', :locals => {:dir_path_choice => @dir_path_choice } %>
</div><br />
<div
<table>
Select Test File:
<!-- Production MiniProd Mounted Watchfolder (Both A3P and A4P Aspera folders in one read location.) -->
<% @files = Dir.glob("/watchfolder/miniprod/hot/**/*.{mpg,mov}").map %>
<%= select_tag 'filepath2', options_for_select(@files, @selected_filepath) %>
</table>
</div><br />
</fieldset>
<div id="holder" style="width:100%">
<% if @file_exists_flag == 'N' %>
<div id="leftValidate" style="float:left; width:50%">
</p>
<p><%= button_tag "Validate File Alias", :type => "submit" %></p>
</div>
<div id="save_btn" style="float:right; width:50%">
<p><%= button_tag "Save File Alias", :type => "submit" %></p>
</div>
<% elsif @file_exists_flag == 'Y' %>
<div id="leftValidate" style="float:left; width:50%">
</p>
<p><%= button_tag "Validate File Alias", :type => "submit" %></p>
</div>
<div id="update_btn" style="float:right; width:50%">
<p><%= button_tag "Update File Alias", :type => "submit" %></p>
</div>
<% else %>
<div id="leftValidate" style="float:left; width:100%">
</p>
<p><%= button_tag "Validate File Alias", :type => "submit" %></p>
</div>
<% end %>
</div>
<% end %>
<body>
<% if @file_exists_flag == 'Y' %>
<span style="color:green;font-weight: bold; font-size:12px; "><%= @file_exists_msg %></span>
<% elsif @file_exists_flag == 'N' %>
<span style="color:red;font-weight: bold; font-size:12px; "><%= @file_exists_msg %></span>
<% else %>
<% @file_exists_msg %>
<% end %>
<fieldset>
<legend>Alias Validation Results:</legend>
<% if @state == "post" %>
<pre>
<label> Alias Generator Version: </label> <%= @aliasgen_ver %>
<label> Alias: </label> <%= @file_alias %>
<% if @file_status == ["F"] %>
<%= 'Validation Status: '%><span style="color:green;font-weight: bold; font-size:12px; "><%= 'Success!' %> </span>
<% else %>
<%= 'Validation Status: '%><span style="color:red;font-weight: bold; font-size:12px; "><%= 'Failed!' %> </span>
<%= 'Error Message: ' %> <%= @file_msg %>
<%= 'Closest Video Alias Match: ' %> <%= @msg_dtl1 %>
<%= 'Closest Audio Alias Match: ' %> <%= @msg_dtl2 %>
<% end %>
<!-- <%= @alias_xml_for %> -->
</pre>
<% end %>
</fieldset><br />
</body>
<fieldset>
<legend>Media Info File and Video Values:</legend>
<% if @state == "post" %>
<pre>
<%= 'File and Path: ' %> <%= @filepathname %> <br />
<%= '======================================================' %>
<%= '= Video Specifications =' %>
<%= '======================================================' %>
<%= 'Video Format: ' %> <%= @video_format %>
<%= 'Video Bit Rate: ' %> <%= @video_bitrate %>
<%= 'Video Width: ' %> <%= @video_width %>
<%= 'Video Height: ' %> <%= @video_height %>
<%= 'Video Frame Rate: ' %> <%= @video_framerate %>
<%= 'Video Aspect Ratio: ' %> <%= @video_aspectratio %>
<%= 'Video Scan Type: ' %> <%= @video_scantype %>
<%= 'Video Scan Order: ' %> <%= @video_scanorder %>
<!-- <%= @media_xml_for %> -->
</pre>
<% end %>
</fieldset><br />
</body>
<fieldset>
<legend>Media Info XML:</legend>
<% if @state == "post" %>
<pre>
<%= @media_xml_for %>
</pre>
<% end %>
</fieldset><br />
</body>
<script>
function render_dir_partial() {
alert('in javascript.');
alert("you chose the option: " + $('form input[type=radio]:checked').val());
radio_button_value = $('form input[type=radio]:checked').val();
alert ("radio_button_value: " + radio_button_value);
if (radio_button_value == 'miniprod') {
$('#dir_list').html('<%=j render :partial => "dir_list", :locals => { :dir_choice => 'miniprod' } %>')
} else if (radio_button_value == 'watch') {
$('#dir_list').html('<%=j render :partial => "dir_list", :locals => { :dir_choice => 'watch' } %>')
} else if (radio_button_value == 'archive') {
$('#dir_list').html('<%=j render :partial => "dir_list", :locals => { :dir_choice => 'archive' } %>')
} else if (radio_button_value == 'local') {
$('#dir_list').html('<%=j render :partial => "dir_list", :locals => { :dir_choice => 'local' } %>')
} else {
$('#dir_list').html('<%=j render :partial => "dir_list", :locals => { :dir_choice => '' } %>')
}
}
</script>
這裏是第一 'dir_list' 部分編碼:
<div>
<label>Select Directory Path:</label><br />
<label>Dir_Choice: </label><%= dir_choice %>
<% if dir_choice== "miniprod" %>
<% @dir_list = Dir["/watchfolder/miniprod/*"] %>
<% elsif dir_choice== "watch" %>
<% @dir_list = Dir["/watchfolder/*"].reject{ |f| f[%r{^/watchfolder/miniprod}] || f[%r{^/watchfolder/aspera_console}]} %>
<% elsif dir_choice== "archive" %>
<% @dir_list = Dir["/archive/*"] %>
<% elsif dir_choice== 'local'%>
<% @dir_list = Dir["/home/silver/test/*"] %>
<% else %>
<% @dir_list = ["/watchfolder/aspera_console/"] %>
<% end %>
<%= select_tag 'dir_list', options_for_select(@dir_list, @selected_dir_list), :onchange => "this.form.submit();", :with => "'dir_list='+this.options[this.selectedIndex].value", :remote => true %>
</div>
這裏是第二下拉框部分 'list_files'。 (注意:@files目錄是硬編碼的,因爲我不知道如何正確地插入@dir)。 #{@ dir}在嵌入式Ruby中不起作用。我嘗試了erb模板,然後出現錯誤「無法將nil轉換爲字符串」。
require 'erb'
<p>
<label>Select Partial Test File:</label><br />
<label>Dir Partial Selected Path Choice: </label><%= dir_path_choice %><br />
<%= @dir_path_choice = params[:dir_list] %>
<label>Partial Path Choice: </label><%= @dir_path_choice %><br />
<% if @dir_path_choice %>
<% @dir = 'Dir.glob("' << @dir_path_choice << '/**/*.{mpg,mov}").map' %>
<% else %>
<% @dir = 'Dir.glob('"/watchfolder/miniprod/hot/**/*.{mpg,mov}"').map' %>
<% end %>
<label>Partial Dir: </label><%= @dir %><br />
<% @files = Dir.glob("/watchfolder/showtimevod/**/*.{mpg,mov}").map %>
<%= select_tag 'filepath', options_for_select(@files, @selected_filepath) %>
</p>
這裏是我的佈局application.html:
(我有jQuery的在那裏從教程之一,請讓我知道,如果我需要與否。)
<!DOCTYPE html>
<html>
<head>
<title>CpOneOffd</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'jquery','application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
注意:我現在有兩次文件選擇框。我將舊的硬編碼版本與<table>
標籤放在一起,然後添加上面的動態部分進行測試,直到我可以使用它。請不要讓這兩個人在查看我的代碼時感到困惑。
有一個驗證文件別名按鈕。用戶選擇文件後,他們然後單擊驗證文件別名,並使用調用2庫文件調用評估媒體方法。一個運行媒體信息並獲取XML,然後將XML傳遞給自定義代碼,以確定內部別名。它現在重新加載帶有URL的網頁,用於評估媒體和顯示的所有媒體數據。
當我選擇目錄時,在更改時評估媒體顯示。它確實表明我的選定值在顯示屏幕中正確傳遞。我只是沒有動態讀取文件。 (我的第二個代碼問題)。您還會注意到我將添加一個保存按鈕並更新按鈕,以將爲該文件顯示的數據保存到表中。
UI快照: