Rails 3 ajax response is not executed

我的未来我决定 提交于 2019-12-11 07:52:19

问题


I am creating a simple ajax feature into my application where a user can increase a "like count" through a link.

I have managed to get the link to run my controller code and the browser is getting a response back, but the response is not executed.

The like link is in partial:

.likes                      
  .like_up                                                                  
    = link_to( image_tag('/images/thumb_up.png'), '/like/' + question.id.to_s, :remote => true)
  #like_count
    = 22# question.likecount                                                
  .like_down
    = link_to( image_tag('/images/thumb_down.png'), '/dislike/' + question.id.to_s, :remote => true)

And it goes into likes_controller:

def up
  @like = current_user.likes.create( :question_id => params[:question_id], :like => true )
  respond_to do |format|
    format.js
  end
end

Then in my up.js.haml I simply have a debug javascript:

alert('2');

and nothing else.

When I press the like link in browser the rails log tels me that it has rendered the js.haml

...
Rendered likes/up.js.haml within layouts/application (104.9ms)
Completed 200 OK in 923ms (Views: 116.3ms | ActiveRecord: 20.1ms)

And when I look at the response the browser gets it certainly looks like the up.js.haml rendered into my application layout where the yield tag is placed.

  <div class='content'>
    alert('2');
  </div>

I suspect that this is not what the browser wants to get back. Also when looking at the firebug console during the ajax request, nothing happens after the request is sent.

Could someone find out why this is not working? Every tutorial and guide I have found does this the same way I'm doing here.


回答1:


First, make sure the content-type is correct:

curl --head -X POST http://localhost:8080/....

I believe the Content-Type should be text/javascript

Second, I think you want to disable the layout so that the DIV doesn't appear in the output.

def up
  @like = current_user.likes.create( :question_id => params[:question_id], :like => true )
  respond_to do |format|
    format.js { render :partial => 'up', :layout => false }
  end
end

Or maybe disable it in the whole controller with

layout false



回答2:


It happened to me in a simple remote form.

Worked after restarting the server even it was the development environment.

Hope I save someone the hour I wasted.

Best regards.



来源:https://stackoverflow.com/questions/6864198/rails-3-ajax-response-is-not-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!