这是 rails 5,希望对某人有所帮助(它仍然适用于 rails 4):
试试这个 ajax 示例:
在'routes.rb'中:
# set the route that ajax can find the path to what controller in backend
get '/admin/some_great_flow', to: 'great_control#great_flow'
在“great_control_controller.rb”控制器中:
# this function in controller will response for ajax's call
def great_flow
# We can find some user or getting some data, model here.
# 'params[:id]' is passed by ajax that we can use it to find something we want.
@user = User.find(params[:id])
# print whole data on terminal to check it correct.
puts YAML::dump(@user.id)
# transform what you want to json and pass it back.
render json: {staff_info: @user }
end
在“app/views/great_control/index.html.erb”视图中:
<div>
<label>Staffs</label>
<%=select_tag(:staff, options_from_collection_for_select(@staffs, :id, :name), id:"staff_id", required: true)%>
</div>
<script>
//every time if option change it will call ajax once to get the backend data.
$("#staff_id").change(function(event) {
let staff_id = $("#staff_id").val()
$.ajax({
// If you want to find url can try this 'localhost:prot/rails/info/routes'
url: '/admin/some_great_flow',
type: 'GET',
dataType: 'script',
data: { id: staff_id },
// we get the controller pass here
success: function(result) {
var result = JSON.parse(result);
console.log(result['staff_info']);
// use the data from backend for your great javascript.
},
});
});
</script>
我自己写的。