weixin_33720078 2015-07-06 12:45 采纳率: 0%
浏览 39

Rails API-AJAX的助手

I have a normal rails app website, but on some pages I need to use AJAX.

I already have some working AJAX Javascript code using jQuery, but so far I haven't used any rails helper to do that, writing strings corresponding to paths manually.

But is there a more convenient way to do it in javascript ? Suppose I have a javascript function which takes an ID as argument, and must call an AJAX action. So far I've been doing it this way

var url = "/tags/tagID"
function getTag(tag_id){
    $.get(url.replace("tagID", tag_id) +'.json')
        .fail(function(data){
            alert('Oops error !');
        })
        .success(function( data ) {blabla ] )
}

Is it possible to rename the .js to .js.erb and use path helpers ? So I could get rid of this url variable and write

routes.rb

resources :tags

tags.js.erb

$.get(tag_path("tagID").replace("tagID", tag_id)....

Or is there a more convenient way to do this ? I only need very little AJAX, so I don't want to use a frontend framework (Angular, etc.), just jQuery

EDIT My scenario

A user searches for a given tag thanks to an autocomplete searchbar. This searchbar will return the ID somehow.

The user can select several tags this way, and their IDs will be stored in an array. Now, upon clicking a button, I want to send a query to a non-RESTful (with the ID array as parameter) controller action via AJAX. For now I will focus on sending one item at a time (so just one ID string), for it is easier/more reactive.

This action is actually going to look in my models for projects and ingeneers that possess this tag, and return a JSON with formatted results.

  • 写回答

1条回答 默认 最新

  • weixin_33691817 2015-07-06 13:04
    关注

    Yes, you can use *.js.erb to use Rails helpers. Rails provides some handy helpers to work with Ajax. Normally with rails you can use them by using the the tag remote: true.

    In your case something like

    <%= link_to 'Tags', tags_path(<tag.id>), remote: true %> (roughly),

    Read more about using Rails helpers with Ajax here, and this explains it nicely.

    Update

    Rails is using CSRF token to validate requests (except GET), so if you are going to use pure HTML/JavaScript, you want to add the token to your request. Have a look at this post on the same.

    I agree there is no out-of-the-box way of doing that, but there are few workarounds.

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘