简体   繁体   English

如何从HTML加载js.erb

[英]How to load js.erb from html

another day, another night spent banging my head over JS and JQuery. 改天,又是一个晚上,我花了很多时间来研究JS和JQuery。

I want to call a page via HTML (and show the route in the header), but have it also load a js.erb script. 我想通过HTML调用页面(并在标题中显示路由),但也要加载js.erb脚本。 Or alternatively, I want to call the js.erb script remotely, but also change the http header to indicate the new route. 或者,我想远程调用js.erb脚本,但还要更改http标头以指示新路由。

I want this because: a) I want to learn and this is frustrating me b) currently, when the user refreshes, his current page doesn't come up, but the one from which the remote => true call came in;; 我之所以这样想是因为:a)我想学习,这让我感到沮丧。b)当前,当用户刷新时,他的当前页面没有显示,但是出现了remote => true调用的页面; it's confusing for the user to go back to a page he doesn't remember. 用户返回到他不记得的页面会感到困惑。

I'm implementing the JQuery.pageless plugin. 我正在实现JQuery.pageless插件。 I call the user/show page remotely and this is what goes into my show.js.erb file: 我远程调用用户/显示页面,这就是我的show.js.erb文件的内容:

$(function(){
$("#container").html("<%= escape_javascript(render '/users/show') %>");
        $('#relationship_list').pageless({ totalPages: "<%= @reviews.count %>"/5+1
                       , url: '/reviews'
                       , params: {id: "<%= params[:id] %>"}
                       , loaderMsg: "loading"
                       });
});

Now this code is A-OK. 现在此代码为A-OK。 it works when called remotely from show.js.erb. 从show.js.erb远程调用时,它可以工作。 The problem is that I want to load the "user show" page via html, and not remotely. 问题是我想通过html而不是远程加载“用户显示”页面。 That means that this script doesn't get loaded. 这意味着该脚本不会被加载。 I need to find another, unobtrusive way to load it. 我需要找到另一种轻松的方式来加载它。

I want to reiterate: there is no bug in the code. 我想重申:代码中没有错误。

Hopefully someone can help. 希望有人可以提供帮助。 Also please note: someone wrote about using the gon gem to address the issue. 另请注意:有人写过使用gon gem解决此问题的文章。 Not for me - I really want to figure this out without gems. 不适合我-我真的很想找出没有宝石的东西。

It sounds like you have the page load working via a remote call (I'm assuming an AJAX GET request after clicking a link or button), which works properly, but the URL doesn't update in the address bar? 听起来您是通过远程调用(在单击链接或按钮后假设AJAX GET请求)来加载页面的,它可以正常工作,但是URL在地址栏中没有更新?

You're looking for the HTML5 pushState() method . 您正在寻找HTML5 pushState()方法

Update your show.js.erb file like so: 像这样更新show.js.erb文件:

$("#container").html("<%= escape_javascript(render '/users/show') %>");

history.pushState(null, "Page Title", "<%= user_path(@user) %>");

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

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