gpt4 book ai didi

javascript - 使用rails如何将 Controller 中的变量同步到 View ,其中 Controller 是更新的发起者

转载 作者:行者123 更新时间:2023-12-03 11:41:05 25 4
gpt4 key购买 nike

我尝试了 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/

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