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.

    评论

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集