简体   繁体   中英

How to pass the attributes in ajax which can be accessed through params in the controller in ruby on rails?

My index.html.erb file looks like: index.html.erb

...
<div class="panel-heading">
    <h4 class="panel-title">                                                
        <li class="list-group-item">
            Post --> <%= post.message %>                                                    
            <%= link_to "Like", 'javascript:void(0)', class: "btn btn-default like-right-position like-btn"%>                                                    
            <span class="like-right-position like-text">Likdfe</span>                                                
        </li>                                                
        <a class="btn btn-info pull-right" data-parent="#accordion1" data-toggle="collapse" href="#collapse-post-<%= post.id %>"> Comments</a>                                            
    </h4>
</div>
...

And my application.js file is:

$('.like-btn').click(function(){
    $.ajax({
        type: "POST",
        url: "like_user_post_path", 
        data: "",
        success: function(result){
            $(".like-text").html(result);
        }
    });
});

I do not understand the concept of data attributes in html and how to pass it through ajax. Thanks in advance!!!

As per the description mentioned in the post, the data attrbutes are the ones which are sent as body for the following POST request via ajax.

$('.like-btn').click(function(){
$.ajax({
    type: "POST",
    url: "like_user_post_path", 
    data: {"field1": "value1", "field2": "value2"},
    success: function(result){
        $(".like-text").html(result);
    }
});
});

Above is an example where the field1 and field2 specify the keys from which you will be parsing over the controller to fetch the corresponding values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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