简体   繁体   中英

Posting data to a rails controller from jquery not working

I am using a JQuery plugin (Plupload) for multiple file uploads on my site. Once the upload completes, I am redirecting the user to an edit page where they can tag and name the photos they just uploaded. I have access to the number of files uploaded (by calling the length on the array that stored the files) and would like to set an instance variable in my photos controller to that so that I can pull the files that were just uploaded.

The redirect is working and the log is showing the parameters as passing the correct integer. Here is what the log shows:

  Started POST "/photos?files=1" for 127.0.0.1 at 2012-03-12 23:09:17 -0400
  Processing by PhotosController#create as JSON
  Parameters: {"files"=>"1"}

Here is the redirect and the post action in the script:

    //redirect after complete
    function attachCallbacks(uploader) {
    uploader.bind('FileUploaded', function(Up, File, Response) {
        if( (uploader.total.uploaded + 1) == uploader.files.length)
             {
             var target = "/photos";
             var filesAdded = uploader.files.length;
             $.ajax({
                type: 'post',
                url: target + '?files='+filesAdded,
                dataType: 'json'
              });
            window.location = "<%=j photos_path %>";
              }
        })
    }

Here is the photos_controller.rb index action where I am trying to set the variable using the parameters:

class PhotosController < ApplicationController
 respond_to :html, :json

 def index
   @data = params[:files]
   @user = current_user
   @photos = current_user.photos
   @photo = Photo.new
 end

I'd like to limit the photos in the view to only show those just added by calling something like:

 @photos = current_user.photos.limit(@data)

Thanks, let me know if you need more info.

No entirely what you intend to do using a variable in a controller -

How about passing the files length in the script when redirecting to photos#index :

window.location = "<%=j photos_path %>"+ '?files=' + filesAdded; 

ie redirect to /photos?files=3 , for 3 files added

Then capturing the files params and limiting photos to be rendered in photos#index :

@photos = current_user.photos.order('created_at DESC').limit(params[:files]) if params[:files].present?

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