gpt4 book ai didi

javascript - 从所选选项的模型中获取属性

转载 作者:行者123 更新时间:2023-12-03 00:54:06 24 4
gpt4 key购买 nike

我有一个员工下拉菜单,其中列出了所有员工。我希望能够选择一名员工并从模型中获取该员工的地址,以便我可以显示它。以下是我的collection_select的代码。

<div class="form-group col-md-2 field">
<%= form.label :employee_id %>
<%= form.collection_select :employee_id, Employee.all, :id, :full_name,{:prompt=>"Select Employee"},{:id=>"emp_select",class:"form-control",:onchange=>"getEmployee();"} %>
</div>

接下来是我用来获取所选员工的值的代码,它确实有效。

function getEmployee() {
var selectedVal=$('#emp_select option:selected').val();}

从这里我该如何获取所选员工的地址?

最佳答案

您必须通过 ajax 调用检索员工的地址。步骤如下:

  1. 在 Rails 应用中定义一个操作,以通过 json 返回员工的地址。
  2. 向该操作发出 ajax 请求并获取所需的信息。
  3. 将结果渲染到 View 中。

有关更多信息,请查看此链接: https://guides.rubyonrails.org/working_with_javascript_in_rails.html

routes.rb

controller :ajax do
get 'ajax/get_employee_address/:employee_id', action: :get_employee_address, as: :get_employee_address
end

ajax_controller.rb

class AjaxController < ActionController::Base
def get_employee_address
employee = Employee.find(params[:employee_id])

render json: employee.address.to_json
rescue ActiveRecord::RecordNotFound
render json: 'Employee not found', status: 422
end
end

你的js代码

function getEmployee() {
var selectedVal=$('#emp_select option:selected').val();
$.ajax({
url: '/ajax/get_employee_address/' + selectedVal,
success: function (address) {
// Render your address to view
},
error: function () {
// Handle error here or just return nothing
return null;
}
})
}

注意:此 ajax 端点会将您的员工地址暴露给外部,因此请务必进行身份验证以防止泄露信息。

关于javascript - 从所选选项的模型中获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52916424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com