简体   繁体   中英

Dealing with ajax request in Rails

Stackoverflow community I have a select in my view. Onchange of which my ajax request is sent.

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

.I am using Jquery ajax. My ajax works. It send an id of rtype to the show_sub_types method.

 $(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", }) }); }); 

In my show_sub_types method I want to grab all subTypes (stypes) from RequestSubType model.

 def show_sub_types @rtype = params[:id]; @stypes = RequestSubType.where("RequestType_id"==@rtype).all respond_to do |format| ... some code here end end 
I do not know how to deal with ajax request, i dont know how to send my stypes array to the page, and how to deal with that response. I have read some tutorials, but still can not understand that respond_to part. Probably i would understand on my own example. In my view i have div where i want to put data send by ajax (inserted into html).

Specify the id of select and read for data attribute. Get that array in data variable, and pass it to post ajax request

 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'
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM