我的应用中有两个不同的页面,它们调用 AJAX 请求来添加新的电话号码(添加到 key_contact
)。这些是公司页面(key_contact own_to company
)和 sales_opportunity 页面(其中 sales_opportunity has_many key_contacts through sale_contacts)。这两个页面都有一个 key_contacts
表,我想在添加电话号码后重新加载该表。我想使用 create.js.erb
文件仅重新加载应该位于页面上的表格(sales_opportunities 上的表格与公司页面上的表格不同 )。因此,我需要测试发送 AJAX 请求的页面的 URL,然后相应地渲染部分内容。我已经尝试过以下方法,但它不起作用。谁能帮我找出原因吗?
//update the key contact table with the new phone number, and close the modal
$('#phone_number_modal').modal('hide')
.clear_previous_errors();
resetForm($('#new_phone_number'));
$input = $('#phone_number_error');
$input.closest('.form-group').removeClass('has-error').find('.warning-block').html('');
//render the newly added key contact to the table if the AJAX call succeeded
<% if (URI(request.referer).path == '/companies') %>
$('#key-contacts-table-div').html("<%= escape_javascript(render :partial => 'shared/key_contacts_table')%>");
<% end %>
<% if (URI(request.referer).path == '/sales_opportunities') %>
$('#sale-contacts-table-div').html("<%= escape_javascript(render :partial => 'sale_contacts/table')%>");
<% end %>
$('.alert').remove();
$('#key-contacts').DataTable({
retrieve: true,
});
最佳答案
您可以在网址中添加额外的 params
,而不是使用 referer
,假设您将其命名为 :action_type
。然后在您的 Controller 中,您可以执行以下操作:
class AAAController < ActionController::Base
def your_action
if params[:action_type] == "companies"
render "create_1"
elsif params[:action_type] == "sales_opportunities"
render "create_2"
end
end
end
然后您可以将不同的逻辑分别放入 create_1.js.erb
或 create_2.js.erb
中。
关于javascript - 如何测试 create.js.erb 文件中哪个页面发送了 AJAX 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32507664/