Javascript not being rendered at script but as html instead

巧了我就是萌 提交于 2019-12-08 06:29:28

The answer to this problem is that in the request headers, the Accept header should have been set to text/javascript or something similar. This should have been done in this js function:

jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});

for POST requests, this was happening just fine, but when I wanted to do a PUT request or a DELETE request, this wouldn't get called somehow or it was being ignored. I realize that using the rails.js plugin for jQuery/AJAX was needed to be referenced since I am using HTML5.

For the edits and deletes to work, I did this to my link_to methods:

link_to "Edit", edit_post_path(post), "data-remote" => 'true', 'data-method' => 'get'      
link_to "Destroy", post , "data-confirm" => 'Are you sure?', "data-remote" => 'true', "data-method" => 'delete'

adding those html attributes to my anchor tags allowed rails.js to determine that I wanted to do some ajax requests with them. They started working after that.

Setting the MIME type manually may be the source of the problem. JavaScript is often sent as application/x-javascript instead of text/javascript so it's best to leave it up to the rendering engine to set that for you.

Also it might be better to use .js.rjs for simple cases like this as it makes your JavaScript largely framework independent.

I ran into the same problem. The solution was to use the script provided here: http://www.danhawkins.me.uk/2010/05/unobtrusive-javascript-with-rails-2-3-5/
All You have to do, after using it as described, to delete an object, is to use something similar to this code:

 <%= link_to "Destroy", post , :confirm => 'Are you sure?', :class => 'remote destroy' %>

For me this works like a charm.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!