简体   繁体   English

使用 AJAX 将参数传递给 Rails 控制器

[英]Issue passing parameter to Rails controller using AJAX

I'm wanting to send a post request from my JavaScript code to my show action in Ruby on Rails which contains data that I want to store in an instance variable so I can save it on a form in my view and upload it to my server.我想从我的 JavaScript 代码向我在 Ruby on Rails 中的 show 操作发送一个 post 请求,其中包含我想要存储在实例变量中的数据,以便我可以将其保存在我视图中的表单上并将其上传到我的服务器.

As you can see below, the parameter 'base64' is showing up in my rails logs, but when I try to call @base64 in my view, after grabbing the value in the controller, it's nil.正如您在下面看到的,参数“base64”显示在我的 rails 日志中,但是当我尝试在我的视图中调用 @base64 时,在获取控制器中的值后,它为零。

Any advice is appreciated, thanks!任何建议表示赞赏,谢谢!

View看法

var full_base64 =  "data:image/jpeg;base64," + base64;

                $.ajax({
                    data: 'base64=' + full_base64,
                    type: 'POST',
                    url: "/videos/show/<%=@video.id%>"
                });

Controller控制器

    def show
        @video = Video.find(params[:id])
        if params[:base64].present?
            @base64 = params[:base64]
        end
    end

Routes路线

post 'videos/show/:id', to: 'videos#show'

Rails server log: Rails 服务器日志:

Started POST "/videos/show/1" for 127.0.0.1 at 2020-01-22 12:59:40 -0600
Processing by VideosController#show as */*
Parameters: {"base64"=>"data:image/jpeg;base64,iV...
...
, "id"=>"1"}

Console安慰

>> 

@base64
=> nil
>> 

If I understand correctly you are trying to pass AJAX to the show action in your controller.如果我理解正确,您正在尝试将 AJAX 传递给控制器​​中的show操作。 This is a very GENERALIZED answer as you have failed to include any of your HTML code and it looks like you don't have a button to fire the AJAX.这是一个非常通用的答案,因为您没有包含任何 HTML 代码,而且您似乎没有触发 AJAX 的按钮。 But I'll try to point you in the right direction.但我会尽力为您指明正确的方向。 You need to do something along the general lines of:您需要按照以下一般路线做一些事情:

var full_base64 =  "data:image/jpeg;base64," + base64;

            $.ajax({
                data: 'base64=' + full_base64,      
                type: 'POST',
                url: "/videos/my_ajax_upload"
            });

That will send your AJAX call to a controller method I've called my_ajax_upload but you can call it whatever you like.这会将您的 AJAX 调用发送到我称为my_ajax_upload的控制器方法,但您可以随意调用它。 In your controller you would need something like:在您的控制器中,您需要类似的东西:

def my_ajax_upload
  @video.update(base_64: params[:base64])
  respond_to do |format|
    format.js {render :action => "base_64_response" }
  end
end 

This responds to the initial AJAX call by saving the param you sent to the DB and replying by calling a file called base_64_response.js.erb which might look something like:这通过保存您发送到数据库的参数并通过调用名为base_64_response.js.erb的文件进行回复来响应初始 AJAX 调用,该文件可能如下所示:

$('#pic_upload').html('<%= escape_javascript(render :partial => 'base_64_response') %>');

Which will render the HTML file called base_64_response.html.erb which needs to contain the html code you want to appear in the page that called it.这将呈现名为base_64_response.html.erb的 HTML 文件,该文件需要包含您希望出现在调用它的页面中的 html 代码。

<div id="pic_upload">
  <%= @base64 =>
</div>

The cycle is load page -> do something to trigger AJAX call to controller method -> process AJAX call with controller method -> render JS file -> JS file replaces div in page with new html循环是load page -> do something to trigger AJAX call to controller method -> process AJAX call with controller method -> render JS file -> JS file replaces div in page with new html

You probably need to read up more on how AJAX works in Rails.您可能需要阅读更多有关 AJAX 在 Rails 中如何工作的信息。 This RailsCast might help http://railscasts.com/episodes/136-jquery-ajax-revised?view=asciicast这个 RailsCast 可能有帮助http://railscasts.com/episodes/136-jquery-ajax-revised?view=asciicast

Just FYI - I have also noticed strange things in Rails if you do not explicitly define the content type.仅供参考 - 如果您没有明确定义内容类型,我还注意到 Rails 中有一些奇怪的事情。 In your posted example you are not stating the contentType and it could be parsing nil for that reason.在您发布的示例中,您没有说明 contentType,因此它可能解析为 nil。 When posting base 64 data you can specify the content type as:发布 base 64 数据时,您可以将内容类型指定为:

               $.ajax({
                    data: 'base64=' + full_base64,
                    type: 'POST',
                    contentType: 'application/octet-stream'
                    url: "/videos/show/<%=@video.id%>"
                });

and it may change what the controller parses for the body.它可能会改变控制器为身体解析的内容。

How to post an image in base64 encoding via .ajax? 如何通过 .ajax 以 base64 编码发布图像?

Just use string instead of symbol for hash key只需使用字符串而不是符号作为哈希键

if params["base64"].present?
  @base64 = params["base64"]
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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