长轮询用PHP和AJAX ......几乎没有

编程入门 行业动态 更新时间:2024-10-10 21:27:15
本文介绍了长轮询用PHP和AJAX ......几乎没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正与一个学校项目。该项目的基本IDE是,我们有一些Arduino的盒子发送一些传感器数据到一个MySQL数据库,我们有一个显示该网站。传感器的数据发送可以说每6秒。

I am working with a school project. The basic ide of the project is, that we have some arduino boxes the sends some sensor data to a mysql db and we have a website that display it. Sensor data is sending lets say every 6sec.

我不有很多用PHP的经验。但我tinkerin我的方式,learing一步step..cowboy风格? =)

I don´t have a lot of experience with PHP. But i am tinkerin my way, learing step by step..cowboy style? =)

的HTML / AJAX / CSS:

<!DOCTYPE html> <html> <head> <title>Arduino event poller</title> <script src="ajax.googleapis/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script> <style type = "text/css" media="screen"> body{ font:13px/1.5 "helvetica neue", helvetica, arial, san-serif; background:#FFF; } #main{ width:430px; height: 300px; display:block; padding:10px 0; float: left; overflow: auto;} .event { display:block; background: #ececec; width:380px; padding:10px; margin:10px; overflow:hidden; text-align: left; } .event img { display:block; float:left; margin-right:10px; } .event p { font-weight: bold; } .event img + p { display:inline; } .patient-name { display:inline; color: #999999; font-size: 9px; line-height:inherit; padding-left: 5px; } .event-text{ color: #999999; font-size: 12px; padding-left: 5px; } .event-timestamp{ color: #000; padding-left: 5px; font-size: 9px;} </style> <script type="text/javascript" charset="utf-8"> var timeStamp = null; /* Simple helper to add some divs.*/ function addevents(patientroom, patientname, eventtyp, timestamp) { $("#main").append( "<div class='event'>" "<p>" + patientroom + "</p>" "<p class='patient-name'>" + patientname + "</p>" "<p class='event-text'>" + eventtyp + "</p>" "<p class='event-timestamp'>" + timestamp + "</p>" "</div>" ); } /*This requests the url "getevents.php" When it complete*/ function waitForEvents() { $.ajax({ type: "GET", url: "getevents.php?timeStamp=" + timeStamp, async: true, /* If set to non-async, browser shows page as "Loading.."*/ cache: false, timeout:50000, /* Timeout in ms */ success: function(data, textStatus, jqXHR) /* called when request to getevents.php completes */ { addevents(data.patientroom, data.patientname, data.eventtyp, data.timestamp); setTimeout( waitForEvents, /* Request next event */ 1000 /* ..after 1 seconds */ ); }, error: function (XMLHttpRequest, textStatus, errorThrown){ alert("Error:" + textStatus + " (" + errorThrown + ")"); setTimeout( 'waitForEvents()', /* Try again after.. */ "5000"); /* milliseconds (5seconds) */ }, }); }; $(document).ready(function(){ waitForEvents(); /* Start the inital request */ }); </script> </head> <body> <div id="main"> </div> </body> </html>

我的后端PHP:

<?php function getEvents() { $con = mysql_connect("localhost","***","***"); if(!con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("arduino_db",$con); $result = mysql_query("SELECT * FROM events ORDER BY eventID DESC LIMIT 1"); if($result) { $patientroom = $row['rumNr']; $patientname = $row['inneboendeNamn']; $eventtyp = $row['handelse']; $timestamp = $row['timestamp']; } if($row) { header('application/json'); echo json_encode($row); exit; } $lastmodif = isset($_GET['timeStamp']) ? $_GET['timeStamp'] : 0; $currentmodif = filemtime($result); while($currentmodif <= $lastmodif) { unsleepp(1000); clearstatcache(); $currentmodif = filemtime($result); } } ?>

我的问题:

  • 如何获取我的每一行从DB和JSON格式的每一行返回到前端的方法waitForEvents。
  • 的例子并不必须是可扩展的,安全的和完整的,它只是需要工作的 =)的

    The example doesn't have to be scaleable, secure or complete, it just needs to work =)

    更新:根据约翰提示新的code。所有我得到是一个空白页,并没有错误。

    UPDATE: new code based on Johns tips. All I gets is a blank page, and no errors.

    推荐答案

    这突然出现给我看的第一件事是有点您的MySQL电话响起。

    The first thing that popped out to me is that your MySQL call is sort of blown.

    在运行这一行:

    $result = mysql_query("SELECT * FROM events ORDER BY eventID DESC LIMIT 1");

    您会得到一个MySQL的资源。你需要利用这让你的行:

    You're going to get a MySQL resource. You need to utilize that to get your row:

    $result = mysql_query("SELECT * FROM events ORDER BY eventID DESC LIMIT 1"); if ($result) { $row = mysql_fetch_assoc($result); if ($row) { // Your result is here, as a big associative array. Each column in your // table is now keyed to this array. Exact fields will depend on your DB. // // Just access it like something like this: $id = $row['id']; $time = $row['time_stamp']; } }

    呼应回了为JSON:

    to echo it back out as JSON:

    ... // snip if ($row) { header('application/json'); echo json_encode($row); exit; } } // handle your errors!

    补充:OP中发现的问题更多的错误的:

    added: Additional error found in OP question:

    // The following line isn't valid. This isn't what you'll get back from $.ajax. // success: function(patientroom, patientname, eventtyp, timestamp) // Corrected code: success: function(data, textStatus, jqXHR) /* called when request to getevents.php completes */ { addevents(data.patientroom, data.patientname, data.eventtyp, data.timestamp); setTimeout( waitForEvents, /* Request next event */ 1000 /* ..after 1 seconds */ ); },

    进一步更新。你混合&放大器;从上面匹配code。

    Further updates. You mixed & matched the code from above.

    $result = mysql_query("SELECT * FROM events ORDER BY eventID DESC LIMIT 1"); if($result) { // this has to go inside of this check. This is where you *ASSIGN* $row. $row = mysql_fetch_assoc($result); // You need to rekey $row before you output: $retVal = array('patientroom'=>$row['rumNr'], 'patientname'=>$row['inneboendeNamn'], 'eventtyp'=>$row['handelse'], 'timestamp'=>$row['timestamp']); // I'm not sure what you're doing with the incoming timestamp. Should we just // return it back out? $retVal['ajax_timestamp'] = $_GET['timeStamp']; header('application/json'); echo json_encode($retVal); exit; // this exits. Comment this out if you want, but don't try to write anything else out to the buffer. } // Not sure what you're trying to do here. I'll comment out for now. /* $lastmodif = isset($_GET['timeStamp']) ? $_GET['timeStamp'] : 0; $currentmodif = filemtime($result); while($currentmodif <= $lastmodif) { unsleepp(1000); clearstatcache(); $currentmodif = filemtime($result); } */

    }

    更多推荐

    长轮询用PHP和AJAX ......几乎没有

    本文发布于:2023-10-10 17:48:10,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1479306.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:几乎没有   长轮询用   PHP   AJAX

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!