저는 웹 프로그래밍에 비교적 익숙합니다. Javascript, PHP, Ajax 등을 처음 접했습니다. Google에서 잠시 동안이 문제에 대한 겉으로보기에는 간단한 해결책을 찾고 있었지만 포기했습니다. 경쟁 조건이 있다고 생각하지만 경쟁 조건과 PHP 및 Javascript와 관련된 모든 사항은 사안별로 솔루션이있는 것 같습니다.가능한 PHP/Javascript 경쟁 조건
다음은 설정입니다. 테이블을 출력하는 PHP 페이지가 있습니다. 테이블 중 하나에있는 행 중 하나에서 셀을 추가 테이블로 채 웁니다. 그것은 5 셀을 가지고 있으며, 기계의 wifi 카드의 신호 강도를 반영하도록 셀의 색상을 변경하고 싶습니다 (현재 두 장의 카드 만 있습니다). 따라서 테이블이 채워지고 셀의 ID가 설정되면 cat/proc/net/wireless에 다른 PHP 코드를 게시하고 호출 한 카드의 신호 강도를 반환하는 javascript 함수를 호출합니다. .
문제 : 무선 카드를 구문 분석하고 셀 ID를 가져 와서 한 카드에 적합한 색상을 설정하는 PHP 코드와 JavaScript. 그러나 PHP에서 태그 내에서 Javascript 함수를 호출하면 마지막 호출 만 수행합니다. 첫 번째는 아무 것도하지 않는 것 같습니다.
내가 완전히 난처한 상황에 빠진거야, 내 모든 Google 검색 조건을 소진 ...
PHP 코드 :
<?php include('assets/header.inc.php'); ?>
<script type="text/javascript" src="<?php echo _JS_?>/ajax_home_display.js"></script>
<div id="cm_body" onload="return false">
<?php
$ap_intf = rtrim(shell_exec("cat /tmp/config | grep AP_DEV | cut -d'=' -f2"));
$mesh_intf = rtrim(shell_exec("cat /tmp/config | grep MESH_DEV | cut -d'=' -f2"));
$uptime = rtrim(shell_exec("uptime | awk '{print $3}' | cut -d',' -f1"));
function display_status_intf($intf, $name)
{
global $uptime;
$packet_success = "100%";
echo "
<tr>
<td style=\"font-size:14px; font-weight:bold;\"><pre>$intf [$name]</pre></td>
<td id=\"sig_status_$intf\">
<table id=\"intf_status\" class = \"list\" cellpadding=10>
<td id=\"sig_st_1_$intf\"></td>
<td id=\"sig_st_2_$intf\"></td>
<td id=\"sig_st_3_$intf\"></td>
<td id=\"sig_st_4_$intf\"></td>
<td id=\"sig_st_5_$intf\"></td>
</table>
<td><pre>$uptime</pre></td></td>
<td style=\"text-align:center;\"><pre id=\"packet_success_$intf\">$packet_success</pre></td>
</tr>
<script>update_interface('$intf')</script>
";
}
// Make a table
echo "<table class=\"list\" cellpadding=1>";
echo "<tr><th>Interface</th><th>Signal Status</th><th>Uptime</th><th>Packet success</th></tr>";
// Make a row on the table for the first wifi card (wifi0)
if ($ap_intf)
display_status_intf($ap_intf, "AP");
// Add a blank row
echo "<tr><td colspan=\"7\" height=\"30px\"></td></tr>";
// Make a row on the table for the second wifi card (wifi1)
if ($mesh_intf)
display_status_intf($mesh_intf, "Mesh");
echo "</table>";
?>
</div>
<?php include('assets/footer.inc.php'); ?>
자바 스크립트 코드 :
THRESH1 = -60;
THRESH2 = -55;
THRESH3 = -50;
THRESH4 = -45;
function update_interface(intf)
{
xmlhttpPost("run_interface_status.php","intf="+intf,interface_stat_response);
}
function interface_stat_response(strQuery,strResponse)
{
var sig_st = [];
// Trim response
var test_return = strResponse;
var intface = strQuery.split("=");
var intf = intface[1];
// Get cell ID's, put in an array sig_st
for (i=1;i<=5;i++)
sig_st[i] = document.getElementById("sig_st_"+i+"_"+intf);
// Reset all colors to default
for (i=1;i<=2;i++)
sig_st[i].setAttribute("style", "background-color:transparent");
if (test_return != "err") {
// Set all colors based on the wifi strength
sig_st[1].setAttribute("style", "background-color:red");
if (test_return > THRESH1)
sig_st[2].setAttribute("style", "background-color:orange");
if (test_return > THRESH2)
sig_st[3].setAttribute("style", "background-color:yellow");
if (test_return > THRESH3)
sig_st[4].setAttribute("style", "background-color:green");
if (test_return > THRESH4)
sig_st[5].setAttribute("style", "background-color:green");
}
}
아약스 무거운 (중요한 경우)
function xmlhttpPost(strURL,strQuery,responseFunc)
{
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
responseFunc(strQuery,self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(strQuery);
}
function trim(s)
{
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
return s;
}
몇 가지 추가 정보 : Firebug는 두 개의 게시물이 각각 정확한 값을 반환한다는 것을 보여주기 때문에 경쟁 조건이라고 생각하지만 응답 함수 (interface_stat_response())의 시작 부분에 중단 점을 배치하면 Firebug 만 후자의 $ intf 및 $ strength 변수 (wifi1의 항목)로 한 번 떨어집니다.
또한 일반적인 포인터가 좋습니다.
JQuery와 포스트 방법, 당신의 AJAX 무거운 교체 시도 ... 3
이 작업을 수행하지 마십시오. 틀렸어. jquery를 사용하거나 색상에 대해 최소한 CSS 클래스를 사용하십시오. – deltree
그냥 작동 시키시겠습니까? 아니면 자바 스크립트를 배우고 싶습니까? 왜냐하면 첫 번째 경우에는 jquery (http://www.jquery.com/)를 사용하려고 할 것이므로 아마도 좋아할 것입니다. 그렇지 않으면 우리는 어쨌든 설명하려고 노력할 것입니다. – giorgio
두 번째 콜백이 실제로 실행되고있는 것으로 의심됩니다. 콜백이 두 번 비동기 적으로 실행 되더라도 방화범이 끊어지기 때문입니다. interface_stat_response 내의 alert 또는 console.log를 사용하여 호출 된 횟수를 정확히 확인하십시오. JS가 2 차 응답에서 항상 실패하면 Firebug 중단 점을 조건부로 만들 수 있으며 두 번째 검사 만 수행하도록 할 수 있습니다. 그러면 화면의 첫 번째 효과를 어느 시점까지보아야합니다. – tomfumb