尽管在rails中呈现,但.js.erb文件仍未执行

时间:2015-07-03 12:41:46

标签: javascript ruby-on-rails

我使用rails和haml。我通过Ajax post将数据发送到rails中的控制器:

$.ajax({
type: 'POST',
url: '/preview-image-upload',
processData: false,
contentType: false,
dataType : 'json',
data: data
});

然后我执行数据并在控制器中渲染js:

respond_to do |format|
 if @previewupload.save
  format.js
 end

正确保存对象。此外,根据服务器日志正确呈现.js.erb文件:

Rendered path/preview_image_upload.js.erb (0.2ms)
Completed 200 OK in 603ms (Views: 8.1ms | ActiveRecord: 8.5ms)

出于测试原因,我在preview_image_upload.js.erb文件中发出警告:

alert("Hello World");

但没有任何反应。它看起来像.js.erb文件已呈现但未执行。

从这里尝试解决方案: js.erb not executing javascript but is processed rails

{ render layout: false, content_type: 'text/javascript' }

但那没用。

2 个答案:

答案 0 :(得分:3)

从jQuery AJAX调用执行Rails javascript响应的数据类型是script

答案 1 :(得分:0)

我找到了解决方案。我只需要删除Ajax请求中的dataType属性。使它看起来像这样:

data = load 'access_log_Jul95' using PigStorage(' ') as (ip:chararray, dash1:chararray, dash2:chararray, date:chararray, date1:chararray, getRequset:chararray, location:chararray, http:chararray, code:int, size:int);

splitDate = foreach data generate  0 AS size:int , ip as ip,  FLATTEN(STRSPLIT(date, ':')) as (h1:chararray,h2:chararray,h3:chararray);

groupedIp = group splitDate by h1;

a = foreach groupedIp generate SUM(splitDate.size);