简体   繁体   中英

Problem rendering vanilla JavaScript in Ruby

In My controller I am trying to render vanilla JavaScript but am getting an unexpected result. This is the code

class UploadController < ApplicationController

    def index

        render :file => 'app\views\upload\uploadfile.rhtml'

    end

    def uploadFile

        render :js => "alert('Hello Rails');"

       post = DataFile.save(params[:upload])

    end

end

Am expecting before executing post = DataFile.save(params[:upload]) I should see a alertbox but I am seeing a download box. What could be the problem?

render :js will send data with the MIME type text/javascript Browsers will see this and attempt to download or display it (my browser, Chromium, displays .js files as plaintext.)

render :js is really meant to return some JavaScript that will be processed by code already on that page.

In essence, you can have an AJAX call from jQuery:

$.ajax({
  type: "POST",
  url: "tokens/1/destroy.js",
  data: { _method: 'DELETE', cell: dsrc.id }
});

This is some code taken from a project of mine. Here, no dataType is defined, so jQuery intelligently "guesses" what type of data is returned. It sees that it is MIME-Type: text/javascript and executes it. Which if we were to use your code, would result in an alert dialog being shown.

In essence, you need to have a page already loaded, and the page has to be waiting for the "vanilla JavaScript" to be returned.

If you just want to execute some code for that particular action, you just have to wrap it using javascript_tag in your template/view, or include an external .js file.

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