在 Rails 4 应用程序中使用 Ajax - 使用 ajax 调用显示下拉选项

Working with Ajax in Rails 4 app- Showing Dropdown Options using ajax call

我正在尝试在我的 rails 应用程序中实现 ajax,根据页面显示的选择会出现一个工作类别下拉列表 jobs.Here 我遇到的问题是已选择类别作业默认显示所有作业。

class JobsController < ApplicationController
 before_action :find_job, only: [:show, :edit, :update, :destroy]
 before_action :authenticate_user!,except:[:index]


 def index
  if params[:jobcategory].blank?
   @jobs = Job.where(active: true).order("created_at DESC")
  else
   @jobcategory_id = Jobcategory.find_by(name: params[:jobcategory]).id
   @jobs =Job.where(jobcategory_id: @jobcategory_id).order("created_at DESC")
  end
  respond_to do |format|
        format.html # show.html.erb
        format.json #{ render json: "testing" }
        format.js # show.js.erb
    end
 end

dropdown.js

$(function(){
 $("#divNewNotifications").on('click', function(){
  $.getScript(this.href);
  return false;
 });
});

_testing.html.haml

- @jobs.each do |job|
 %div{class: "col-md-3"}
  %div{class: "thumbnail"}
   %div{class: "caption"}
    %h3= link_to job.title, job
    %h4= job.company
    %h6= job.location 

index.js.erb

$(function(){
 $("#testing").html("<%= j (render("testing")) %>");
});

index.html.haml

%hearder
 %nav.navbar.navbar-job
  .container{class: "text-center"}
   %div{class: "btn-group"}
    %ul.dropdown
     %a.btn.dropdown-toggle.btn-job{"data-toggle" => "dropdown","role" => "button"}
      Jobs
      %span{class: "caret",id: "dropdown_title"}
     %ul.dropdown-menu{id: "divNewNotifications"}
      %li= link_to "All Creative Jobs", jobs_path
      - Jobcategory.all.each do |jobcategory|
       %li= link_to jobcategory.name, jobs_path(jobcategory: jobcategory.name),remote: true
  
        
%body
%div{id:"testing"}
 = render 'testing'
  

Rails.application.routes.draw do
  get 'errors/filenot_found'

  get 'errors/unprocessable'

  get 'errors/internal_server_error'

  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
  devise_for :users

  resources :jobs do
    collection do
      get 'all'
    end
  end

  root 'jobs#index'

  get "/404" => "errors#file_not_found"
  get "/422" => "errors#unprocessable"
  get "/500" => "errors#internal_server_error"

end

您正在 <ul id="divNewNotifications"> 包装器而不是链接上设置事件侦听器。

$(function(){
    $("#divNewNotifications").on('click', function(){
        $.getScript(this.href);
        return false;
    });
});

如果您将选择器传递给 jQuery.on,它将处理子节点的事件:

$(function(){
    $("#divNewNotifications").on('click', 'a', function(){
        $.getScript(this.href);
        return false;
    });
});