不能读取property 'top'未定义的Ruby on Rails项目

Cannot read property 'top' of undefined Ruby on Rails project

本文关键字:Ruby on Rails 项目 未定义 读取 不能读 不能 top property      更新时间:2023-09-26

首先-我已经阅读了SO上所有其他线程的相同错误。他们没有一个人帮我一点忙。

:

  1. 在新客户页面,填写字段,点击保存
  2. 在customer_controller中Fire off方法创建
  3. 将json与info返回到页面:

    格式。json {render:json => res.to_a}

  4. Page获取数组:

    阵列[2]新:851

是一个格式正确的数组。

错误:

Uncaught TypeError: Cannot read property 'top' of undefined 

追踪来源:

$.ajax({
    type : "POST",
    url : "/customers",
    data : dataString,
    dataType : "json",
    success : function(data) {
      console.log(data);
      // data = data[0];
      // console.log(data);
      if (data[0] == 'error' || data[0] == 'i') {
        $("#flash_message").addClass("alert-error");
        $("#flash_message").html("<p>" + data[1] + "</p>");
        $('html,body').animate({
          scrollTop : $("#flash_message").offset().top
        }, 'slow');
      } else {
        $("#flash_message").addClass("alert-success");
        $("#flash_message").html("<p>" + data[0] + "</p>");
        $('html,body').animate({
          scrollTop : $("#flash_message").offset().top

flash_message是吗?让我们看看视图:

<% flash.each do |key, value| %>
<div id="flash_message" class="alert alert-<%= key %>">
    <%= value %>

是的,这里肯定有一个flash_message id。

然而,我们正在使用布局-所以一定有一个时间问题。AJAX代码位于admin.html.erb布局中,我们正在从customer.html.erb视图中完成NEW客户操作。客户控制者有:

  layout 'admin', :except => [:show]

"show"不是我们这里讨论的方法——我们使用的是"create"

Processing by CustomersController#create as JSON

那么为什么我们不知道"flash_message"是什么呢?

我在尝试从网页获取大小或位置时遇到了时间问题。在大多数情况下,问题确实是对象尚未完成加载,因此还不知道数据。

正如Cherniv所提到的,我还认为您可能需要使用load事件,因为ready事件在页面(因此也是所需的布局)完成加载之前被触发。直到整个页面完成后才触发加载事件,因此您的数据应该可用。

这是堆栈溢出的另一个解释:load-ready事件

Ok update on this -尽管这段代码:

<% flash.each do |key, value| %>
<div id="flash_message" class="alert alert-<%= key %>">
    <%= value %>
<%end%>

这里的kicker是我的愚蠢-我们甚至没有在Rails中使用FLASH来处理这些消息!!

我们通过AJAX调用向浏览器返回一个JSON对象,该调用是对客户控制器内的一个方法进行的(哇——这有点拗口)。

所以我的JSON找不到"flash_message"因为它不存在除非我调用Rails中的flash方法

我必须为"标准"类型的消息创建另一个div。现在我不确定为什么我的团队开发了两种将消息打印回窗口的方法,但这是另一个主题…

<% flash.each do |key, value| %>
<div id="flash_message" class="alert alert-<%= key %>">
    <%= value %>
<%end%>
<div id="flash_message" class="alert" style="display:none" />

我们给它一个display:none样式,因为"alert"类在整个页面上留下了这个难看的黄色条(bootstrap的好!)

所以答案是我从来没有调用过flash。每个,并且div仅在调用flash时存在。每一个都是印刷出来的,骗过了我的眼睛,但并没有真正出现。

专业提示:总是点击实际页面上的"查看源代码",而不是连续几天盯着你的代码看。