简体   繁体   English

如何在JavaScript中使用Ajax变量和Rails方法

[英]How to use an ajax variable and a rails method in javascript

I'm passing created_at back to my view with the data.when variable. 我正在将created_at与data.when变量一起传递回我的视图。

I now want to use the time_ago_in_words function on this data. 我现在想在此数据上使用time_ago_in_words函数。

My failed attempt: 我失败的尝试:

<script>
 $('.new_short_message').bind('ajax:success', function(xhr, data, status) {
 $( this ).before( '<p>' + "<%= time_ago_in_words(data.when) %>" + '</p>' );
 });
</script>

This works without the rails function (but I want to get time ago in words) 这可以在没有rails功能的情况下工作(但我想在时间上讲些时间)

<script>
$('.new_short_message').bind('ajax:success', function(xhr, data, status) {
 $( this ).before( '<p>' + data.when + '</p>' );
});
</script>

In Rails: 在Rails中:

Using ajax send data.when to receptive controller and get that desire 'words' in this view . 使用ajaxdata.when发送到接收控制器,并在此view获得该愿望的“单词”。

In JavaScript 在JavaScript中

Use this function to get time_ago_in_word in javascript. 使用此函数在javascript中获取time_ago_in_word I got this code here . 我在这里获得此代码。 So thanks to boxnos . 因此,感谢boxnos

var time_ago_in_words = function(from, to) {
 to = to ? to : Date.now();

var minutes = (to - from) / 60000;

var data = [
 [0 , 'less than a minute ago'],
 [1 , 'a minute ago'],
 [2 , function(m) {return m.toFixed() + ' minutes ago';}],
 [45 , 'about 1 hour ago'],
 [90 , function(m) {return 'about ' + (m / 60).toFixed() + ' hours ago';}],
 [1440 , '1 day ago'],
 [2880 , function(m) {return (m / 1440).toFixed() + ' days ago';}],
 [43200 , 'about 1 month ago'],
 [86400 , function(m) {return (m / 43200).toFixed() + ' months ago';}],
 [52960 , 'about 1 year ago'],
 [1051200, function(m) {return (m / 525960).toFixed() + ' years ago';}],
 [Number.MAX_VALUE]
];

function b_search(value, lower, pos, upper) {
 if (data[pos][0] <= value && value < data[pos + 1][0])
  return data[pos];
 else if (value < data[pos][0])
  return b_search(value, lower, Math.floor((lower + pos - 1) / 2), pos - 1);
 else
  return b_search(value, pos + 1, Math.floor((pos + 1 + upper) / 2), upper);
}

var res = b_search(minutes, 0, Math.floor((data.length - 1) / 2), data.length - 1)[1];
 return (res instanceof Function) ? res(minutes) : res;
};

You should always use the escape_javascript method to escape strings. 您应该始终使用escape_javascript方法对字符串进行转义。 Like This: 像这样:

<script>
 $('.new_short_message').bind('ajax:success', function(xhr, data, status) {
 $( this ).before( '<p>' + "<%= escape_javascript(time_ago_in_words(data.when)) %>" + '</p>' );
 });
</script>

Otherwise this can cause format failures that cause javascript syntax errors. 否则,这可能会导致格式错误,从而导致javascript语法错误。

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

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