Jquery ajax调用在Rails中已经呈现的部分内部无效

时间:2011-04-11 20:22:15

标签: jquery ruby-on-rails ajax

我在Jquery + Rails中使用了很棒的Nicolas Alpi指令,其中我的application.js是:

jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})


function _ajax_request(url, data, callback, type, method) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
        });
}

jQuery.extend({
    put: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});

/*
Submit a form with Ajax
Use the class ajaxForm in your form declaration
<% form_for @comment,:html => {:class => "ajaxForm"} do |f| -%>
*/
jQuery.fn.submitWithAjax = function() {
  this.unbind('submit', false);
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  })

  return this;
};



/*
Retreive a page with get
Use the class get in your link declaration
<%= link_to 'My link', my_path(),:class => "get" %>
*/
jQuery.fn.getWithAjax = function() {
  this.unbind('click', false);
  this.click(function() {
    $.get($(this).attr("href"), $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

/*
Post data via html
Use the class post in your link declaration
<%= link_to 'My link', my_new_path(),:class => "post" %>
*/
jQuery.fn.postWithAjax = function() {
  this.unbind('click', false);
  this.click(function() {
    $.post($(this).attr("href"), $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

/*
Update/Put data via html
Use the class put in your link declaration
<%= link_to 'My link', my_update_path(data),:class => "put",:method => :put %>
*/
jQuery.fn.putWithAjax = function() {
  this.unbind('click', false);
  this.click(function() {
    $.put($(this).attr("href"), $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

/*
Delete data
Use the class delete in your link declaration
<%= link_to 'My link', my_destroy_path(data),:class => "delete",:method => :delete %>
*/
jQuery.fn.deleteWithAjax = function() {
  this.removeAttr('onclick');
  this.unbind('click', false);
  this.click(function() {
    $.delete_($(this).attr("href"), $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

/*
Ajaxify all the links on the page.
This function is called when the page is loaded. You'll probaly need to call it again when you write render new datas that need to be ajaxyfied.'
*/
function ajaxLinks(){
    $('.ajaxForm').submitWithAjax();
    $('a.get').getWithAjax();
    $('a.post').postWithAjax();
    $('a.put').putWithAjax();
    $('a.delete').deleteWithAjax();
}

$(document).ready(function() {
// All non-GET requests will add the authenticity token
 $(document).ajaxSend(function(event, request, settings) {
       if (typeof(window.AUTH_TOKEN) == "undefined") return;
       // IE6 fix for http://dev.jquery.com/ticket/3155
       if (settings.type == 'GET' || settings.type == 'get') return;

       settings.data = settings.data || "";
       settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(window.AUTH_TOKEN);
     });

  ajaxLinks();
});

我的任务控制器有:

 def followship
    @task = Task.find(params[:id])

    respond_to do |format|
        # some logic
        format.js {render :content_type => 'text/javascript' }
    end
  end

我的followship.js.erb:

<% if @new_follower %>
  $("#followers_list").append("<%= escape_javascript(render :partial => 'new_follower', :object => @new_follower, :locals => {:task => @task}) %>");
  $("#_user_id option[value='<%= @new_follower.id.to_s %>']").remove();
  $("#follower_<%= @new_follower.id.to_s %>").delay(500).effect("highlight", {}, 2000);
<% else %>
   $("#follower_<%= @id_to_remove %>").fadeOut("slow");
<% end %>
<% flash.discard %>

_new_follower.erb partial:

<li id='follower_<%= @new_follower.id.to_s %>'>
  <%= @new_follower.name %>
  <%= link_to "[x]", {:controller => "tasks", :action => "followship", :id => @task, :user_id => @new_follower.id, :to_do => "exclude"}, :class => "get" if @new_follower == current_user %>
</li>

问题:

当我在任务中包含一个新的关注者时,一切正常。新的li将呈现给列表并突出显示新用户。但是当我尝试使用[x]链接排除自己时,使用最后一个ajax调用传递的小部分进行渲染,页面被重新加载,只有脚本的文本呈现在屏幕上:(例如)

$("#follower_2").fadeOut("slow");

如果我重新加载页面并且在不使用部分的情况下渲染新的关注者,一切都会正常。 fadeOut有效。

请帮忙。提前致谢。 顺便说一句:Rails 2.3.8

1 个答案:

答案 0 :(得分:0)

对application.js使用这种方法解决了我的问题:

http://www.danhawkins.me.uk/2010/05/unobtrusive-javascript-with-rails-2-3-5/

感谢。