RAILS不渲染js.erb

时间:2017-08-05 15:09:07

标签: javascript ruby-on-rails ajax ruby-on-rails-5

以下是工作流程:

从root_page.js开始

document.addEventListener('DOMContentLoaded', function() {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function (data) {
    // code
};
httpRequest.open('GET', '/contents/ajax_rss.js', true);
httpRequest.send();
})

这会发送ajax请求,该请求已成功路由到内容#ajax_rss

def ajax_rss
  respond_to do |format|
    format.js {
    }
  end
end

并且应该呈现以下ajax_rss.js.erb

document.getElementById("rss").innerHTML = "HELLO WORLD!";

这是服务器响应:

Processing by ContentsController#ajax_rss as JS
User Load (0.9ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? 
ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
Rendering contents/ajax_rss.js.erb
Rendered contents/ajax_rss.js.erb (1.1ms)
Completed 200 OK in 9ms (Views: 5.0ms | ActiveRecord: 0.9ms)

但文字没有相应显示。我错过了什么?这是我第一次尝试使用remote时从表单或按钮调用的AJAX:

所有远程:true调用按预期工作。

2 个答案:

答案 0 :(得分:1)

remote: true选项使客户端能够执行从服务器返回的js。这是您需要修复的部分。

您可以将回复传递给eval(response)。 请参阅:Calling a JavaScript function returned from an Ajax response

答案 1 :(得分:0)

您可以使用eval:

来完成
  request = new XMLHttpRequest();
  request.onreadystatechange = function()
  {
      if (request.readyState == 4 && request.status == 200)
      {
          eval(request.responseText);
      }
  };
  request.open('GET', '/contents/ajax_rss.js');
  request.send();