gpt4 book ai didi

javascript - Rails 中的文章统计小部件

转载 作者:行者123 更新时间:2023-12-02 20:43:43 25 4
gpt4 key购买 nike

我一直在尝试为我的 Rails 应用程序设计一个小部件,不幸的是发现自己缺乏 Javascript 技能......

我能够根据此博客的简短指南创建一个小部件:http://www.eduvoyage.com/2008/8/3/widget-with-rails

但是我需要的与他们描述的有点不同。

如果您有一个类似于 digg 或 tweetmeme 的应用程序,其中包含对特定文章的投票,您如何创建一个小部件来显示投票?

假设文章模型有名称、链接和 votes_counter。

这是我尝试过的:

在文章 Controller 中:

    def index
@article = Article.find_by_link("#{request.url}")
respond_to do |format|
format.js
format.html
end
end

在index.js.erb中:

var txt = ''

txt += "<div id='article_widget'>";
txt += "<h2>Article vote count:</h2>";
txt += "<%= escape_javascript(@article.votes) %>";
txt += "</div>";

document.write(txt);

我遇到的问题是 @article 结果为零。为了找出问题所在,我将这段代码添加到我的 javascript 文件中:

txt += "<%= escape_javascript(request.url) %>";

屏幕上的结果是:http://localhost:3000/articles.js 。显然,当 find_by_link 方法仅返回 javascript 文件的路径时,我将无法使用它。我在 find_by_link 方法中想要的是浏览器中的当前 url。

或者有更好的方法吗?

有没有办法让我的 Rails 应用确切地知道引用了哪篇文章?

最佳答案

许多小部件实际上运行两段代码:如下所示:

客户端站点上的小部件代码:

<script src="http://yourdomain.com/javascripts/widget.js" type="text/javascript"></script>

widget.js:

(function(){
var loc = window.location,
title = document.title,
href = 'http://yourdomain.com/widgets/count.js?url=' + encodeURIComponent( loc );

href = href + '&title=' + encodeURIComponent( title );

var script = document.createElement('script');
script.src = href;
script.type = "text/javascript";

// Call your real script:
document.documentElement.firstChild.appendChild( script );
})();

然后您可以使用 params[:url]params[:title] 在 Rails 中访问它

这不是一个完整的解决方案,因为您的第二个脚本没有关于放置小部件的位置的上下文。大多数大型应用程序(digg、tweetmeme)都使用 document.write,但我个人不太喜欢使用它。

如果我正在构建整个东西,我可能会有一个空的 div,其 id 是您拥有用户副本的小部件代码的一部分,或者我可能会在第一个中使用 document.write js 文件写入第二个脚本可以通过 getElementById 填充的保持 div

最后一句警告:请务必在匹配之前清理 URL。您不希望 http://domain.comhttp://domain.com/ 提供两个不同的匹配项。

关于javascript - Rails 中的文章统计小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1843779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com