作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试了 AJAX 中的长轮询,客户端以一定的时间间隔调用服务器请求数据。 - UI中列表的更新是由客户端发起的
下面是代码:
服务器 Controller .rb
@@x=0
def results
@@x++
render :json => @@x
end
index.html.erb
<button id='get_value' class="btn">Run</button>
<ul id="value_variable_from_controller"><ul>
$(document).ready(function() {
var getPoll=function getValue(trigger) {
$.ajax({
type: 'GET',
url: '/server/results/',
success: function(data, status) {
if (data < 50){
$('#value_variable_from_controller').append("<li>"+data+"</li>");
setTimeout(getValue(true), 1000);}},})}
$(document).on("click","#get_value",getPoll);
问题是,在 Controller 有权启动/发送数据并且 HTML 上的列表同步更新/附加的情况下,我该如何做相反的事情?
最佳答案
这做起来比较棘手,因为您需要额外的技术。 HTTP 及其 request-respond模型无法做到这一点。客户端(浏览器)无法接收来自服务器的请求。
您最终将得到双向通信,因为首先客户端向服务器询问事情,然后服务器要求客户端更新。用于执行此操作的技术是 websockets 。 Rails 不包含此功能,因此您需要通过 gems ( websockets-gem ) 或/并且事件驱动的非阻塞服务器(如 node.js)添加它也很有用。
有不同的教程可以帮助您入门。 Here这是一个带有两个漂亮的小图形的示例,它解释了这种情况。
关于javascript - 使用rails如何将 Controller 中的变量同步到 View ,其中 Controller 是更新的发起者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26270048/
我是一名优秀的程序员,十分优秀!