简体   繁体   English

如何在 js 文件中使用 rails 路径进行 GET 和 ajax 调用?

[英]How to use rails paths in js files for GET's and ajax calls?

I have a link that toggles description lengths between short and long.我有一个链接可以在短和长之间切换描述长度。

Initially I created it with a call from a js file, ie just最初我通过一个 js 文件的调用创建了它,即

# /app/assets/javascripts/toggle_length.js
$.get('/toggle_full_details');

That works fine.这很好用。 (it uses css classes to show/hide long and short descriptions). (它使用 css 类来显示/隐藏长短描述)。

But ideally I want to use a rails route for the link.但理想情况下,我想为链接使用 rails 路线。

Which are (partial listing for relevant route):哪些是(相关路线的部分清单):

$ rake routes
    Prefix               Verb  URI Pattern                     Controller#Action
    ...
    toggle_full_details  GET   /toggle_full_details(.:format)  links#toggle_full_details
    toggle_row_shading   GET   /toggle_row_shading(.:format)   links#toggle_row_shading
    ...
    root                 GET   /                               links#index

So I renamed my long_or_sort_details.js file to be long_or_short_details.js.erb and tried using a rails route but none of the below attempts worked, what am I missing / doing wrong?所以我将我的long_or_sort_details.js文件重命名为long_or_short_details.js.erb并尝试使用 rails 路线,但以下尝试均long_or_short_details.js.erb ,我错过了什么/做错了什么?

$.get({ "<%= toggle_full_details_path %>" }) 
// Gave: undefined local variable or method toggle_full_details_path

$.get({"<%= toggle_full_details_url %>"}); 
// Gave: undefined local variable or method toggle_full_details_url

$.ajax({url:"/toggle_full_details", type: 'GET' }) 
// Works ok... but not using routes :(

$.ajax({ url:'<%= toggle_full_details_path %>', type: 'GET' }) 
// undefined local variable or method `toggle_full_details_path'

fyi my app/assets/javascripts/applications.js includes the file with仅供参考,我的app/assets/javascripts/applications.js包含该文件

//= require long_or_short_details

This worked for me:这对我有用:

$.get("<%= Rails.application.routes.url_helpers.toggle_full_details_path %>"); 

I don't want any user message if the call fails, hence no $.ajax and success: or failure: calls.如果调用失败,我不想要任何用户消息,因此没有$.ajaxsuccess:failure:调用。

If I had wanted additional stuff for success or failure one could use something like:如果我想要额外的成功或失败的东西,可以使用类似的东西:

$.ajax({
  url: "<%= Rails.application.routes.url_helpers.toggle_full_details_path %>",
  type: 'GET',
  success: function(r) {
    $('span#messages').html('<span class="ok">yes</span>');
  },
  error: function(r) {
    $('span#messages').html('<span class="not_ok">no</span>');
  }
});

Another option might be to use the js-routes gem which "Brings Rails named routes to javascript"另一种选择可能是使用js-routes gem,它“将 Rails 命名路由带到 javascript”

https://github.com/railsware/js-routes https://github.com/railsware/js-routes

If you are using webpacker , you might want to check out js_from_routes , which allows you to generate helper methods to make AJAX requests.如果您正在使用webpacker ,您可能需要查看js_from_routes ,它允许您生成辅助方法来发出 AJAX 请求。

If you are using jQuery you could use a custom template that targets jQuery , and then:如果您使用的是 jQuery,则可以使用针对 jQuery自定义模板,然后:

resources :links do
  get :toggle_full_details, on: :collection, export: true
end
import LinksRequests from '@requests/LinksRequests'

LinksRequests.toggleFullDetails({ success: onSuccess, error: onError })

However, you can achieve a nicer API by using axios .但是,您可以使用axios实现更好的 API。

LinksRequests.toggleFullDetails().then(onSuccess).catch(onError)

Benefits:好处:

  • Easily specify which routes should generate a helper.轻松指定应生成帮助程序的路由。
  • No need to manually specify the URL and HTTP verb, preventing mistakes and saving development time.无需手动指定 URL 和 HTTP 谓词,防止错误并节省开发时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM