简体   繁体   English

在link_to远程之后的Rails Ajax回调

[英]Rails ajax callback after link_to remote

I'm trying to figure out this ajax callback business, and haven't had any luck getting it to work. 我正在尝试弄清楚这个ajax回调业务,并且没有运气能使它正常工作。 I've looked at tons of SO questions, tutorials, etc. but am apparently not grasping how this works. 我看过无数的SO问题,教程等,但显然没有掌握其工作原理。 I'm trying to update the contents of a div that contains a partial. 我正在尝试更新包含部分内容的div的内容。 This is a standard like/unlike type function where the user will click on link and it should update the icon via ajax. 这是一个标准的like / unlike类型功能,用户将单击链接,并且应该通过ajax更新图标。 My ajax remote requests are working fine, but I can't get the callbacks to work. 我的ajax远程请求运行正常,但无法使回调正常工作。 Here's my show.html.erb file: 这是我的show.html.erb文件:

<table class="v-table">
    <tr>    
        <td>
            <div class="favorite">
                    <%= render 'vendors/favorite' %>
            </div>
        </td>
        <td><h2><%= image_tag @vendor.image_url %></h2></td>
        <td><%= @vendor.address %></td>
    </tr>
</table>

Here's the partial favorite : 这是部分favorite

<% if current_user.voted_for?(@vendor) %>
    <%= link_to image_tag("Heart (2).png"), 
        { :controller => :vendors, 
        :action => 'vote_against_vendor', :vendor_id => @vendor.id},
        { :method => 'delete', :remote => true }%>
<% else %>
    <%= link_to image_tag("Heart (1).png"), 
        { :controller => :vendors, 
        :action => 'vote_for_vendor', :vendor_id => @vendor.id},
        { :method => 'post', :remote => true} %>
<% end %>

Here's my relevant controller actions: 这是我相关的控制器操作:

respond_to :js

def show

    @vendor = Vendor.find_by_id(params[:id])
end

def vote_for_vendor

    vendor = Vendor.find(params[:vendor_id])
    current_user.vote_for(vendor)
    render :toggle
end

def vote_against_vendor

    vendor = Vendor.find(params[:vendor_id])
    current_user.unvote_for(vendor)
    render :toggle
end

My toggle.js.erb file: 我的toggle.js.erb文件:

$("#favorite").html("<%= escape_javascript render('favorite') %>");

I'm really new to using js and ajax, please help! 我真的是使用js和ajax的新手,请帮忙! Thanks in advance. 提前致谢。

ERROR LOG 错误日志

After committing my remote transaction correctly, I get this error: 正确提交远程事务后,出现以下错误:

Rendered vendors/_favorite.html.erb (1.3ms)
  Rendered vendors/toggle.js.erb (2.6ms)
Completed 500 Internal Server Error in 47ms

ActionView::Template::Error (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id):
    1: <% if current_user.voted_for?(@vendor) %>
    2:  <%= link_to image_tag("Heart (2).png"), 
    3:      { :controller => :vendors, 
    4:      :action => 'vote_against_vendor', :vendor_id => @vendor.id},
  app/views/vendors/_favorite.html.erb:1:in `_app_views_vendors__favorite_html_erb___385976980778737159_2184308220'
  app/views/vendors/toggle.js.erb:1:in `_app_views_vendors_toggle_js_erb___3800164439665893406_2169792040'
  app/controllers/vendors_controller.rb:39:in `vote_for_vendor'


  Rendered /Users/User/.rvm/gems/ruby-2.0.0-p195/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.7ms)
  Rendered /Users/User/.rvm/gems/ruby-2.0.0-p195/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.3ms)
  Rendered /Users/User/.rvm/gems/ruby-2.0.0-p195/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (11.1ms)

Not sure what this means: ActionView::Template::Error (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id): 不确定这是什么意思: ActionView::Template::Error (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id):

OK, you need to assign the model to an instance not local variable in your controller. 好的,您需要将模型分配给instance而不是控制器中的local变量。

@vendor = Vendor.find(params[:vendor_id])

The rest looks good to me. 其余的对我来说看起来不错。

Not sure but I guess you may be missing render 'vendors/favorite' in your toggle.js.erb file. 不确定,但我想您可能会在toggle.js.erb文件中缺少渲染“供应商/收藏夹” Everything else seems to be okay for me. 其他一切对我来说似乎还可以。

Ajax is the client side way to send server a request and get a response in several commands. Ajax是客户端发送服务器请求并通过多个命令获得响应的客户端方法。 You should do the calling on the client side (so mainly write code on javascript or client side language). 您应该在客户端进行调用(因此主要是使用javascript或客户端语言编写代码)。

Don't forget that ajax is an asynchronous by default (you can change it - not recommanded at first try. Actually when you send your request to server, you go to next line of your code, and the response is recieved not exactly at the expected time, as usual programs). 不要忘记默认情况下ajax是异步的(您可以更改它-第一次尝试时不建议使用。实际上,当您将请求发送到服务器时,您转到代码的下一行,并且接收到的响应不完全是预计时间,与通常的程序一样)。

Here is a tinny code: 这是一个细小的代码:

var tout;
....

function checkAjax() {
    'use strict';

    var xmlhttp;

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            if (tout) {
                clearTimeout(tout);
            }
// do something
        }
    };

    function ajaxTimeout() {
        xmlhttp.abort();
// write error to client
    }

    clearTimeout(tout); // if tout is global.

    tout = setTimeout(function () {
        ajaxTimeout();
    }, 10000); // 10 seconds, or what you persume to be fine.

    xmlhttp.open("POST", "test.php", true); // it can be "GET" or aspx, or whatever.
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xmlhttp.send("");
}

Good luck!!! 祝好运!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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