每隔几秒刷新一次服务器代码并更新表单元素

时间:2021-06-08 01:16:57

To start off here's how the application works: (note: there are multiple users on the page like Patient M, Patient E, so on)

从这里开始,应用程序的工作原理如下:(注意:页面上有多个用户,例如患者M,患者E,等等)

1) Next to Patient X's name is a button labeled Check In. This is logged in the server side.

1)患者X旁边的名称是一个标记为“检入”的按钮。这是在服务器端记录的。

2) Upon clicking the Check In button , the user is then presented with a dropdown (replacing the initial button) with the multiple locations the user could choose. Upon selecting a location from the select, the server side is updated again.

2)单击“检入”按钮后,将向用户显示用户可以选择的多个位置的下拉列表(替换初始按钮)。从选择中选择位置后,再次更新服务器端。

3) The user then might decide to choose multiple locations, repeating step 2

3)然后用户可能决定选择多个位置,重复步骤2

4) At the end, when the user is done selecting locations, he clicks on the Check Out button in the same select where the user had clicked locations in steps 2 and 3, titled Check Out. Upon clicking this, it is sent to checkloc.php and logged.

4)最后,当用户完成选择位置时,他点击用户在步骤2和3中单击位置的同一选择中的“检出”按钮,标题为“检出”。单击此按钮后,会将其发送到checkloc.php并进行记录。

5) Finally, the dropdown dissapears and the words Checked Out appear.

5)最后,下拉消失并出现Checked Out字样。

Unfortunately, the problem is that right now if I am Computer 1, and go through the process of clicking Check In, selecting a location, and checking out, this is completely apart from Computer 2 doing this.

不幸的是,现在的问题是,如果我是计算机1,并且经历了单击“检入”,选择位置和检出的过程,这与计算机2完全不同。

Heres a diagram:

下图:

每隔几秒刷新一次服务器代码并更新表单元素

So basically I need a way to grab the server code every few seconds and update the form elements with the current values. I'm a pretty new programmer, so code and tutorials would be extra helpful. Also, like I just mentioned, I am a new programmer, so if my code could be cleaned up in any ways that would be fantastic.

所以基本上我需要一种方法来每隔几秒获取服务器代码并使用当前值更新表单元素。我是一个非常新的程序员,所以代码和教程会更有帮助。另外,就像我刚才提到的,我是一个新的程序员,所以如果我的代码可以以任何方式清理,那将是非常棒的。

Thanks for any and all help! I'm glad to clarify any questions you have!

感谢您的帮助!我很高兴澄清你有任何问题!

Heres the code:

继承人代码:

<script src="http://code.jquery.com/jquery-1.8.2.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$('.locationSelect').hide();  // Hide all Selects on screen
$('.finished').hide();        // Hide all checked Out divs on screen
$('.checkOut').hide();

$('.checkIn').click(function() {
    var $e = $(this);
    var data = $e.data("param").split('_')[1] ;
    // gets the id  of button
    // You can map this to the corresponding button in database...
    $.ajax({
        type: "POST",
        url: "checkin.php",
        // Data used to set the values in Database
        data: { "checkIn" : $(this).val(), "buttonId" : data},
        success: function() {
            // Hide the current Button clicked
            $e.hide();
            // Get the immediate form for the button
            // find the select inside it and show...
            $('.locationSelect').show();
            $('.checkOut').show();
        }
    });
});

$('.locationSelect').change(function() {
    $e = $(this);
    var data = $e.data("param").split('_')[1] ;
    // gets the id  of select
    // You can map this to the corresponding select in database...
    $.ajax({
        type: "POST",
        url: "changeloc.php",
        data: { "locationSelect" : $(this).val(), "selectid" : data},
        success: function() {
            // Do something here
        }
    });
});

$('.checkOut').click(function() {
    var $e = $(this);
    var data = $e.data("param").split('_')[1] ;
    // gets the id  of button
    // You can map this to the corresponding button in database...
    $.ajax({
        type: "POST",
        url: "checkout.php",
        // Data used to set the values in Database
        data: { "checkOut" : $(this).val(), "buttonId" : data},
        success: function() {
            // Hide the current Button clicked
            $e.hide();
            $('.locationSelect').hide();
            // Get the immediate form for the button
            // find the select inside it and show...
            $('.finished').show();
        }
    });
});

});
</script>

and html:

和HTML:

<button class="checkIn" data-param="button_9A6D43BE-D976-11D3-B046-00C04F49F230">Check In</button>

<form method='post' class='myForm' action=''>
  <select name='locationSelect' class='locationSelect' data-param="location_9A6D43BE-D976-11D3-B046-00C04F49F230">
    <option value="0">Select a location</option>
    <option value='1'>Exam Room 1</option>
    <option value='2'>Exam Room 2</option>
    <option value='3'>Exam Room 3</option>
    <option value='4'>Exam Room 4</option>
  </select>
</form>
<button class="checkOut" data-param="cbutton_9A6D43BE-D976-11D3-B046-00C04F49F230">Check Out</button>

<div class='finished' style='color:#ff0000;'>Checked Out</div>

heres the server side code ( I split it into three pages just for testing)

继承人服务器端代码(我把它分成三页只是为了测试)

checkin.php

checkin.php

<?php

date_default_timezone_set('America/Denver');

$apptid = $_REQUEST['buttonId'];
$currentlocationstart = date("Y-m-d H:i:s"); 

if(isset($_REQUEST['checkIn'])){
    $checkin = 0;
}


$hostname = 'localhost';

$username = '*******';

$password = '******';


$conn = new PDO("mysql:host=$hostname;dbname=sv", $username, $password);

$sql = "UPDATE schedule SET currentlocation = ?, currentlocationstart = ? WHERE apptid= ? ";
$q = $conn->prepare($sql);
$q->execute(array($checkin,$currentlocationstart, $apptid));


?>

locationchange.php

locationchange.php

<?php

date_default_timezone_set('America/Denver');

$apptid = $_REQUEST['selectId'];
$currentlocationstart = date("Y-m-d H:i:s"); 

if(isset($_REQUEST['locationSelect'])){
    $currentLocation = $_REQUEST['locationSelect'];
}


$hostname = 'localhost';
$username = '*****';
$password = '*******';


$conn = new PDO("mysql:host=$hostname;dbname=sv", $username, $password);

$sql = "UPDATE schedule SET currentlocation = ?, currentlocationstart = ? WHERE apptid= ? ";
$q = $conn->prepare($sql);
$q->execute(array($currentlocation,$currentlocationstart, $apptid));

?>

and checkout.php

和checkout.php

<?php

date_default_timezone_set('America/Denver');

$apptid = $_REQUEST['buttonId'];
$currentlocationstart = date("Y-m-d H:i:s"); 

if(isset($_REQUEST['checkOut'])){
    $checkin = 1000;
}


$hostname = 'localhost';

$username = '*********';

$password = '********';


$conn = new PDO("mysql:host=$hostname;dbname=sv", $username, $password);

$sql = "UPDATE schedule SET currentlocation = ?, currentlocationstart = ? WHERE apptid= ? ";
$q = $conn->prepare($sql);
$q->execute(array($checkin,$currentlocationstart, $apptid));


?>

4 个解决方案

#1


6  

You are referring to a methodology known as a "heartbeat". I am going to post an example here, but first I'd like to give you a few pointers since, as you said, you are a new dev :).

您指的是一种称为“心跳”的方法。我将在这里发布一个例子,但首先我想给你一些指示,因为你说,你是一个新的开发人员:)。

1) With JQuery, try to avoid using the class selector. It's notoriously slow. Use the id selector wherever possible, or the nodename selector with a narrowed search scope if it isn't possible. The browser uses the ID as a sort of "index" or "key" to the dom element, so it is the fastest search.

1)使用JQuery,尽量避免使用类选择器。这是出了名的慢。尽可能使用id选择器,如果不可能,则使用带有缩小搜索范围的节点名选择器。浏览器使用ID作为dom元素的“索引”或“键”,因此它是最快的搜索。

2) PRELOAD! Even if you are going to use class selectors, don't do

2)PRELOAD!即使你打算使用类选择器,也不要这样做

    $('.locationSelect')

Over and over. If you are going to reference the same DOM element more than once, do this:

一遍又一遍。如果要多次引用相同的DOM元素,请执行以下操作:

    var locationSelect = $('.locationSelect'); //this creates a reference
    $(locationSelect).whatever() //this uses the reference

By doing this, you are only searching the DOM once. It won't seem like a big deal with smaller apps, but as your app becomes more and more complicated, it takes more and more time to search to DOM for elements. By using a reference, you only search once.

通过这样做,您只搜索DOM一次。对于较小的应用程序来说,这似乎不是什么大问题,但随着您的应用程序变得越来越复杂,搜索到DOM的元素需要花费越来越多的时间。通过使用引用,您只需搜索一次。

3) (Optional) I would RECOMMEND using an MVC platform like AngularJS (which is written by Google). MVC, or Model View Controller, allows you to update a "Model" (basically a JavaScript Object) and the "View" (the HTML) automatically adjusts its value using something called UI-Bindings. It's a great way to go about developing an app from the get-go, but if you are already knee-deep in plain-jane code, it may not be practical for you. I'd still take a look at their tutorial to see what it could offer you: http://docs.angularjs.org/tutorial/

3)(可选)我建议使用像AngularJS这样的MVC平台(由Google编写)。 MVC或模型视图控制器允许您更新“模型”(基本上是JavaScript对象),“视图”(HTML)使用称为UI-Bindings的东西自动调整其值。这是一个从一开始就开发应用程序的好方法,但如果你已经熟悉普通的代码,那么对你来说可能并不实用。我仍然会看看他们的教程,看看它能为你提供什么:http://docs.angularjs.org/tutorial/

Now on to your original question! Yes, this is completely possible with jQuery by using a methodology known as a heartbeat. A heartbeat allows you to emulate data persistence between the server and client. The more frequent the heartbeat, the more in-sync your clients will be, but the greater load on your webserver as well. It's a balancing act.
In a nutshell, it works something like this:

现在回答你原来的问题吧!是的,通过使用称为心跳的方法,jQuery完全可以实现。心跳允许您模拟服务器和客户端之间的数据持久性。心跳越频繁,客户端的同步性就越高,但网络服务器的负载也越大。这是一种平衡的行为。简而言之,它的工作原理如下:

    setInterval(function(){
        $.ajax({
           url: 'heartbeatscript.php',
           method: 'post'
           //whatever data you want to send
        }).done(function(data){
           //do whatever with the returned result
        });
    },heartbeatInterval); //heartbeatInterval will be however many MS you want    

I would also recommend using JSON to communicate between the client and server. JSON is easy to parse on both ends, and on the client end it is simply the fastest mechanism for parsing bulk data. JSON is parsed directly into a JavaScript object because the notation is literally what JS uses to store object Data within the browser anyway. XML is also a good choice. Both are very easy to get started with:

我还建议使用JSON在客户端和服务器之间进行通信。 JSON很容易在两端解析,而在客户端,它只是解析批量数据的最快机制。 JSON被直接解析为JavaScript对象,因为符号实际上是JS用来在浏览器中存储对象数据的方式。 XML也是一个不错的选择。两者都很容易上手:

Client Side: You can use jQuery to parse rudimentary XML:

客户端:您可以使用jQuery来解析基本的XML:

    $('nodeName',xml);

You can parse JSON into a JSO like this:

您可以将JSON解析为JSO,如下所示:

    var JSO = JSON.parse(JSONString);                           

#2


5  

Have a look at Socket.IO, because as the site says:

看看Socket.IO,因为该站点说:

What is Socket.IO?

Socket.IO aims to make realtime apps possible in every browser and mobile device

Socket.IO旨在使每个浏览器和移动设备中的实时应用程序成为可能

Although Socket.IO is in NodeJS/Javascript, there's quite an conversation about using PHP with Socket.IO

虽然Socket.IO在NodeJS / Javascript中,但是有很多关于将PHP与Socket.IO一起使用的讨论

#3


2  

Basically it seems what you are looking to do is to update data from one machine on another machine without the need to do a page reload.

基本上,您要做的就是从另一台机器上的一台机器更新数据,而无需进行页面重新加载。

It is good that you already have some familiarity with AJAX, as that will probably be one of the ways you can implement your solution. What you are needing, in essence, is to poll the server from the webpages at some specified interval (maybe every second or every few seconds depending on your need). You can do this using AJAX.

你已经对AJAX有一定的了解,这很好,因为这可能是你实现解决方案的方法之一。实质上,您需要的是在某个指定的时间间隔(可能是每秒或每几秒,根据您的需要)从网页轮询服务器。你可以使用AJAX来做到这一点。

When you poll this server, you can pull down data (HTML fragments, JSON data, whatever makes sense in your application) and use this data to update the page. So when a user makes an update on Computer 1, Computer 2 will be able to poll the server and pull in updates related to the data changes on Computer 1.

轮询此服务器时,您可以下拉数据(HTML片段,JSON数据,应用程序中有意义的任何内容)并使用此数据更新页面。因此,当用户在计算机1上进行更新时,计算机2将能够轮询服务器并提取与计算机1上的数据更改相关的更新。

#4


2  

It's one of the basic principles of a web application that every action is initiated at the client, i.e. if you want to change the display at one of the computers, someone would have to click something on that computer. Originally there was no possibility to update the display on the second computer if something happens on the server, and there is still no trivial solution.

这是Web应用程序的基本原则之一,即每个操作都是在客户端启动的,即如果您想要更改其中一台计算机的显示,则有人必须单击该计算机上的某些内容。如果服务器上发生了某些事情,最初没有可能更新第二台计算机上的显示器,并且仍然没有简单的解决方案。

However, with modern browsers several technologies have been developed and are in widespread use among web mail clients and responsive "Web 2.0" applications. You would have to decide on one of them and implement them yourself, each of them having its pros and cons.

然而,在现代浏览器中,已经开发了几种技术并且在web邮件客户端和响应“Web 2.0”应用程序中广泛使用。您将不得不决定其中一个并自己实施,每个都有其优点和缺点。

The one easiest to implement (apart from a simple "refresh" button) is probably to do an AJAX request every few seconds and update the screen according to the current user state that the server reports.

最容易实现的(除了简单的“刷新”按钮)可能每隔几秒就做一次AJAX请求,并根据服务器报告的当前用户状态更新屏幕。

#1


6  

You are referring to a methodology known as a "heartbeat". I am going to post an example here, but first I'd like to give you a few pointers since, as you said, you are a new dev :).

您指的是一种称为“心跳”的方法。我将在这里发布一个例子,但首先我想给你一些指示,因为你说,你是一个新的开发人员:)。

1) With JQuery, try to avoid using the class selector. It's notoriously slow. Use the id selector wherever possible, or the nodename selector with a narrowed search scope if it isn't possible. The browser uses the ID as a sort of "index" or "key" to the dom element, so it is the fastest search.

1)使用JQuery,尽量避免使用类选择器。这是出了名的慢。尽可能使用id选择器,如果不可能,则使用带有缩小搜索范围的节点名选择器。浏览器使用ID作为dom元素的“索引”或“键”,因此它是最快的搜索。

2) PRELOAD! Even if you are going to use class selectors, don't do

2)PRELOAD!即使你打算使用类选择器,也不要这样做

    $('.locationSelect')

Over and over. If you are going to reference the same DOM element more than once, do this:

一遍又一遍。如果要多次引用相同的DOM元素,请执行以下操作:

    var locationSelect = $('.locationSelect'); //this creates a reference
    $(locationSelect).whatever() //this uses the reference

By doing this, you are only searching the DOM once. It won't seem like a big deal with smaller apps, but as your app becomes more and more complicated, it takes more and more time to search to DOM for elements. By using a reference, you only search once.

通过这样做,您只搜索DOM一次。对于较小的应用程序来说,这似乎不是什么大问题,但随着您的应用程序变得越来越复杂,搜索到DOM的元素需要花费越来越多的时间。通过使用引用,您只需搜索一次。

3) (Optional) I would RECOMMEND using an MVC platform like AngularJS (which is written by Google). MVC, or Model View Controller, allows you to update a "Model" (basically a JavaScript Object) and the "View" (the HTML) automatically adjusts its value using something called UI-Bindings. It's a great way to go about developing an app from the get-go, but if you are already knee-deep in plain-jane code, it may not be practical for you. I'd still take a look at their tutorial to see what it could offer you: http://docs.angularjs.org/tutorial/

3)(可选)我建议使用像AngularJS这样的MVC平台(由Google编写)。 MVC或模型视图控制器允许您更新“模型”(基本上是JavaScript对象),“视图”(HTML)使用称为UI-Bindings的东西自动调整其值。这是一个从一开始就开发应用程序的好方法,但如果你已经熟悉普通的代码,那么对你来说可能并不实用。我仍然会看看他们的教程,看看它能为你提供什么:http://docs.angularjs.org/tutorial/

Now on to your original question! Yes, this is completely possible with jQuery by using a methodology known as a heartbeat. A heartbeat allows you to emulate data persistence between the server and client. The more frequent the heartbeat, the more in-sync your clients will be, but the greater load on your webserver as well. It's a balancing act.
In a nutshell, it works something like this:

现在回答你原来的问题吧!是的,通过使用称为心跳的方法,jQuery完全可以实现。心跳允许您模拟服务器和客户端之间的数据持久性。心跳越频繁,客户端的同步性就越高,但网络服务器的负载也越大。这是一种平衡的行为。简而言之,它的工作原理如下:

    setInterval(function(){
        $.ajax({
           url: 'heartbeatscript.php',
           method: 'post'
           //whatever data you want to send
        }).done(function(data){
           //do whatever with the returned result
        });
    },heartbeatInterval); //heartbeatInterval will be however many MS you want    

I would also recommend using JSON to communicate between the client and server. JSON is easy to parse on both ends, and on the client end it is simply the fastest mechanism for parsing bulk data. JSON is parsed directly into a JavaScript object because the notation is literally what JS uses to store object Data within the browser anyway. XML is also a good choice. Both are very easy to get started with:

我还建议使用JSON在客户端和服务器之间进行通信。 JSON很容易在两端解析,而在客户端,它只是解析批量数据的最快机制。 JSON被直接解析为JavaScript对象,因为符号实际上是JS用来在浏览器中存储对象数据的方式。 XML也是一个不错的选择。两者都很容易上手:

Client Side: You can use jQuery to parse rudimentary XML:

客户端:您可以使用jQuery来解析基本的XML:

    $('nodeName',xml);

You can parse JSON into a JSO like this:

您可以将JSON解析为JSO,如下所示:

    var JSO = JSON.parse(JSONString);                           

#2


5  

Have a look at Socket.IO, because as the site says:

看看Socket.IO,因为该站点说:

What is Socket.IO?

Socket.IO aims to make realtime apps possible in every browser and mobile device

Socket.IO旨在使每个浏览器和移动设备中的实时应用程序成为可能

Although Socket.IO is in NodeJS/Javascript, there's quite an conversation about using PHP with Socket.IO

虽然Socket.IO在NodeJS / Javascript中,但是有很多关于将PHP与Socket.IO一起使用的讨论

#3


2  

Basically it seems what you are looking to do is to update data from one machine on another machine without the need to do a page reload.

基本上,您要做的就是从另一台机器上的一台机器更新数据,而无需进行页面重新加载。

It is good that you already have some familiarity with AJAX, as that will probably be one of the ways you can implement your solution. What you are needing, in essence, is to poll the server from the webpages at some specified interval (maybe every second or every few seconds depending on your need). You can do this using AJAX.

你已经对AJAX有一定的了解,这很好,因为这可能是你实现解决方案的方法之一。实质上,您需要的是在某个指定的时间间隔(可能是每秒或每几秒,根据您的需要)从网页轮询服务器。你可以使用AJAX来做到这一点。

When you poll this server, you can pull down data (HTML fragments, JSON data, whatever makes sense in your application) and use this data to update the page. So when a user makes an update on Computer 1, Computer 2 will be able to poll the server and pull in updates related to the data changes on Computer 1.

轮询此服务器时,您可以下拉数据(HTML片段,JSON数据,应用程序中有意义的任何内容)并使用此数据更新页面。因此,当用户在计算机1上进行更新时,计算机2将能够轮询服务器并提取与计算机1上的数据更改相关的更新。

#4


2  

It's one of the basic principles of a web application that every action is initiated at the client, i.e. if you want to change the display at one of the computers, someone would have to click something on that computer. Originally there was no possibility to update the display on the second computer if something happens on the server, and there is still no trivial solution.

这是Web应用程序的基本原则之一,即每个操作都是在客户端启动的,即如果您想要更改其中一台计算机的显示,则有人必须单击该计算机上的某些内容。如果服务器上发生了某些事情,最初没有可能更新第二台计算机上的显示器,并且仍然没有简单的解决方案。

However, with modern browsers several technologies have been developed and are in widespread use among web mail clients and responsive "Web 2.0" applications. You would have to decide on one of them and implement them yourself, each of them having its pros and cons.

然而,在现代浏览器中,已经开发了几种技术并且在web邮件客户端和响应“Web 2.0”应用程序中广泛使用。您将不得不决定其中一个并自己实施,每个都有其优点和缺点。

The one easiest to implement (apart from a simple "refresh" button) is probably to do an AJAX request every few seconds and update the screen according to the current user state that the server reports.

最容易实现的(除了简单的“刷新”按钮)可能每隔几秒就做一次AJAX请求,并根据服务器报告的当前用户状态更新屏幕。