Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jquery-ujs.js(rails.js)便利だよって話

== 自前でやる場合

=== HTML

<a href="/some_action" class="some-action">some action</a>

=== Javascript

$('a.some-action').live('click', function() {
  var self = $(this);
  var url = self.attr('href');
  var csrf_token = $('meta[name=csrf-token]').attr('content');
  $.ajax({url: url, type: 'POST', data: {authenticity_token: csrf_token}})
    .success(function() {
      // 成功時の後処理
    })
    .error(function() {
      // 失敗時の後処理
    });
});

== Rails.js に乗っかる場合

=== HTML

<a href="/some_action" class="some-action" data-remote="true" data-method="post">some action</a>

=== JavaScript

// 自分でやらなくてもtype や csrf token を良い感じに処理してくれる
$('a.some-action').live('ajax:success', function() {
  // 成功時の後処理
}).live('ajax:error', function() {
  // 失敗時の後処理
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment