Why I need add “data: {type: ”script“}” on remote link with rails / ajax

空扰寡人 提交于 2019-12-01 18:04:12

问题


in one project of mine, the code:

  = link_to "add", new_me_category_path, class: "btn btn-success", remote: true

can load remote form correctly.

But some one can not work, browser did not execute the responese js code. I need to add "data: {type: "script"}" like this :

  = link_to "add", new_me_category_path, class: "btn btn-success", remote: true, data: {type: "script"}

I want to know the reason.


回答1:


Im not JS expert, and I dont know Ruby, but i think:

When datatype is set to script - downloaded code is loaded and executed immediately.

When datatype is default (html) - downloaded code is just loaded into browser. You have to execute it "manually" (by calling some function for example).

If your code has just some functions for use with previously loaded code - these functions will be available and will work (when data type is html).

If there are defined events in your code - they will not work because they are not initialized, becuase code was not executed.

If my explanation is bad - you may read about difference between jQuery.get() and jQuery.getScript() methods.




回答2:


Behind the scenes, jQuery's ajax method is used: http://api.jquery.com/jquery.ajax/ by uJS https://github.com/rails/jquery-ujs whenever the data-remote="true" attribute of the link is set, which is done by remote: true.

As stated in the documentation, Ajax determines the HTTP Accepts header sent and interprets the return value based on the dataType and accepts arguments passed to ajax(), which here are taken from the data- attributes of the anchor by uJS.

If no dataType is set through the data-type attribute, jQuery inferences the request and response type "intelligently". This can explain inconsistencies if you do not explicitly specify it.




回答3:


If you loading script correct template should have .ejs extension (or render raw script like this: render js: 'some code'). You must escape html using j in ejs template like this:

template.ejs

$('some selector').html('<%= j render('some template') %>');

Please give me also url. Correct one should end with .js.



来源:https://stackoverflow.com/questions/15041506/why-i-need-add-data-type-script-on-remote-link-with-rails-ajax

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