在 Rails 中处理 ajax 请求

Dealing with ajax request in Rails

本文关键字:ajax 请求 处理 Rails      更新时间:2023-09-26

Stackoverflow community我有一个选择。发送我的 ajax 请求的更改。

		<%= f.select :id, options_from_collection_for_select(@rtypes, "id", "typeName"), 
{include_blank: true },																				
{'data-rtypes': @rtypes.to_json } %>		

.我正在使用Jquery ajax。我的 ajax 工作。它将 rtype 的 id 发送到 show_sub_types 方法。

$(function () {
   // specify id or class for your select tag   
   $('select').on('change', function () {
		var rtype = $(this).val();
    $.ajax({
    url: "/RequestTypes/show_sub_types/"+rtype,
    type: "GET",
  })
   });
});

在我的show_sub_types方法中,我想从 RequestSubType 模型中获取所有子类型(类型)。

def show_sub_types
	@rtype = params[:id];
	@stypes = RequestSubType.where("RequestType_id"==@rtype).all
         respond_to do |format|
	 ... some code here
         end
	end
我不知道如何处理 ajax 请求,我不知道如何将我的 stypes 数组发送到页面,以及如何处理该响应。我已经阅读了一些教程,但仍然无法理解respond_to部分。也许我会以我自己的例子来理解。在我看来,我有div 我想放置 ajax 发送的数据(插入到 html 中)。

指定selectid并读取data属性。 在数据变量中获取该数组,并将其传递给 ajax 请求

 var data = $(this).data('rtypes');
 or
 $(this).find(':selected').data('rtypes')
 $.ajax({
   type : "POST",
   url :  "/RequestTypes/show_sub_types/"+rtype,
   dataType: 'json',
   data: JSON.stringify(data),
   dataType: "json", 
   contentType: 'application/json'
});