【发布时间】:2018-06-05 13:09:30
【问题描述】:
问题
我目前在我的models/listing.rb 中有一个方法,它的方法如下:
def self.lookup_info(val)
# Fetch some data from the internet
return{ price: value1, title: value2, isbn: val }
end
当用户在创建新列表时将val 插入views/listings/_form.html.erb 时,我想调用lookup_info 并让它填写表单的其余部分,如果返回结果(不是零)。
设置
控制器/listings_controller.rb
def new
@listing = Listing.new
end
views/listings/new.html.erb
<%= render 'form', listing: @listing %>
views/listings/_form.html.erb(我在实际代码中使用了 div 标签,但为简单起见不包括在下面)
<%= form_for(@listing, :html => {class: "form-horizontal" , role: "form"}) do |f| %>
<%= f.label :isbn, "ISBN" %>
<%= f.text_field :isbn , class: "form-control" , id: "isbn_field", placeholder: "ISBN (10 or 13 digits - no dashes)", autofocus: true %>
<%= f.label :price, "Price" %>
<%= f.text_field :price , class: "form-control" , id: "price_field", placeholder: "Price" %>
<%= f.label :title, "URL" %>
<%= f.text_field :title , class: "form-control" , id: "title_field", placeholder: "Title" %>
<%= f.submit class: "btn btn-primary btn-lg" %>
<% end %>
当用户输入 users_isbn 时,我需要什么 javascript 和 rails 来更新 _form.html.erb,我调用 lookup_info(users_isbn),然后获取更新的部分,以便将字段的值设置为结果。
响应示例:
<%= form_for(@listing, :html => {class: "form-horizontal" , role: "form"}) do |f| %>
<%= f.label :isbn, "ISBN" %>
<%= f.text_field :isbn , class: "form-control" , id: "isbn_field", placeholder: "ISBN (10 or 13 digits - no dashes)", value: lookup_info(users_isbn)[:isbn] autofocus: true %>
<%= f.label :price, "Price" %>
<%= f.text_field :price , class: "form-control" , id: "price_field", placeholder: "Price", value: lookup_info(users_isbn)[:price] %>
... <!-- Same idea for title -->
<% end %>
当前开始使用 Javascript
这是我目前所拥有的:
_form.js.erb(不确定这是否是 js 文件的正确名称)
var isbnField = document.getElementById('#isbn_field').value;
if (isbnField.length == (10 || 13)){
var ajaxResponse = $.ajax({
url: "listings/lookup",
type: 'GET',
data: {isbn: $('#isbn_field').val()}
});
ajaxResponse.success(function(){
alert("Success"); # I would actually want to <%= j render #name of form partial with values %>
});
ajaxResponse.error(function(){
alert("Could not find that ISBN");
});
}
【问题讨论】:
标签: ruby-on-rails ajax methods