2013-08-18 64 views
0

我想刷新两个名为profittext和sumtext的变量,每隔几秒刷新并在以下位置进行回显。我知道AJAX需要做到这一点,但我怎么才能使它工作?我发现的唯一方法是刷新整个文件的内容。有没有什么办法刷新特定的变量?任何答案将不胜感激。非常非常感谢你。每秒刷新一个变量

<table> 
if($profitandloss<$zero) { 
    $profitText = "<div style=\"color: red;\">$profitandloss</div>"; 
} elseif ($profitandloss>$zero) { 
    $profitText = "<div style=\"color: green;\">$profitandloss</div>"; 
} 
// for profit and loss counting 

$sum+= $profitandloss; 
// 

echo "<tr><td>" . $row['trade_id'] .   
     "</td><td>" . $row['selection'] . 
     "</td><td>" . $row['date'] . 
     "</td><td>" . $row['type'] . 
     "</td><td>" . $row['size'] . 
     "</td><td>" . $row['bidprice'] . 
     "</td><td>" . $row['offerprice'] . 
     "</td><td>" . $row['stoploss'] . 
     "</td><td>" . $row['takeprofit'] . 
     "</td><td>" . $profitText . 
     "</td><td><a href ='delete.php?id=". 
     $row['trade_id']."'>X</a> 
    </td></tr>"; 

$profitandloss=0; 

if($sum<$zero) { 
    $sumText = "<div style=\"color: red;\">$sum</div>"; 
} elseif ($sum>$zero) { 
    $sumText = "<div style=\"color: green;\">$sum</div>"; 
} 
} 
echo "</table><br>"; 
?> 
<!DOCTYPE html> 
<html> 
<table style="border:1px solid black;"> 
<tr> 
<th style="border:1px solid black;">Profit/Loss</th> 
</tr> 
<tr> 
<td style="border:1px solid black;"><?php echo $sumText ;?></td> 
</tr> 
</table> 
</html> 
+0

下面的答案给你一个良好的开端。你也可以使用一个包装这个功能的JavaScript库。看看这个熟悉 - http://api.jquery.com/load/ – JohnP

回答

0

你会needd两个PHP页面: - 一个用HTML和JS,其中定期对使Ajax调用,并将结果向HTML - 第二位你的动态数据块的json(甚至是纯文本)输出

不幸的是,在答案中写出完整的代码并不是人们在做stackoverflow的时候,所以看看下面的小例子,并试图找出ou缺少的部分。

http://jsfiddle.net/AMEqz/

var xhr = new XMLHttpRequest(); 
xhr.onload = function(r) { 
    // your render logic HERE 
    setTimeout(send, 1000); 
} 
function send() { 
    xhr.open("GET", "/", true); 
    xhr.send(); 
} 
send(); 

PS:记住,每一个Ajax请求将意味着你的服务器额外的连接,所以一定要确保它可以处理的负荷;)

+0

你是什么意思的渲染逻辑?即时通讯不是精通JavaScript! – nigel

+0

将数据放入html的部分,因此对用户可见。 ('b.innerText'在我的小提琴的情况下) – c69

+0

我真的不知道如何做到这一点...我将不胜感激,如果你能帮助我 – nigel

2

我的概念挣扎当我第一次开始时如何构造这样的代码。虽然它不是特定于您的特定变量,但下面是如何使用jQuery/PHP通过AJAX更新var的简单示例。

序幕:如果这是你将要经常做的事情,你要学习jQuery的,而不是单独使用普通的JavaScript。关于如何学习jQuery,有很多很棒的免费资源。另外,如果你对在线免费教程不满意,this是一本很好的书。我将在jQuery中编写示例。

设计:好了,所以它的工作方式是这样的:

  • 在JavaScript中设置一个计时器,以执行特定的功能每X秒(你不想做的每一秒钟)。

  • 该函数对服务器上的.PHP文件进行AJAX调用(使用jQuery),向其发送必要的数据,以便.PHP代码知道要发回的内容。

  • .PHP代码抓取所需的数据(例如,使用MySQL)以JSON格式对其进行编码,然后退出。

  • 对AJAX调用的承诺被触发,并从PHP发送的数据被接收。如你所愿处理它。

  • 从第2步

如果你有什么代码做任何的问题重复,请询问。

AJAX。PHP

<?php 

$mysqli = new mysqli("localhost", "my_user", "my_password", "world"); 

$return_obj = array(); 
$request_obj = NULL; 

// our AJAX call used "POST" as it's 'type', so we look in that 
// variable. 
if (array_key_exists("func",$_POST)) { 

    if ($_POST['func'] === "get_update") { 

     if (array_key_exists("which_var",$_POST)) { 

      $which_var = $_POST['which_var']; 
      $which_var = $mysqli->real_escape_string($which_var); // should use prepared statements 

      // we sent 'num_people_logged_in' as our value here, so we'll be looking for a column/field 
      // with that value. this assumes that some other code, somewhere else, 
      // is regularly updating the table. it also assumes that there will only 
      // be a single row returned, which will hold the value. 
      $query = "SELECT '$which_var' FROM site_stats "; 
      if ($result = $mysqli->query($query)) { 

       if ($row = $result->fetch_assoc()) { 
        $request_obj[$which_var] = $row[$which_var]; 
       } 
      } 
     } 
    } 
} 

$return_obj['request'] = $request_obj; 
echo json_encode($return_obj); 
die(); 

?> 

MYCODE.JS

// this actually sends the AJAX request to the server. 
function getUpdate() { 

    var jqXHR = $.ajax({   
     url : "ajax.php", 
     data : { 
      'func' : 'get_update', 
      'which_var' : 'num_people_logged_in' 
     }, 
     dataType : 'json', 
     type : 'POST', 
     timeout : 10000 
    }); 

    // attach 'promises' to the jqXHR object, which represents 
    // the AJAX call itself. 'promises' are, in this context, 
    // just events. 

    jqXHR.done(function(data,textStatus,jqXHR) {   

     // this executes if the AJAX call succeeded. 
     // the variable 'data' holds what the server 
     // sent us. 
     if ((data) && (data.request)) { 
      receiveUpdate(data.request); 
     } 
    }); 

    jqXHR.fail(function(jqXHR,textStatus,errorThrown) { 

     // this executes if it failed 
     console.log("Fail: " + textStatus + " (" + errorThrown + ")"); 
    }); 

    jqXHR.always(function(a,textStatus,c){      

     // this executes either way, after .done or .fail 
    }); 
} 

// this is called from jqXHR.done, on success 
function receiveUpdate(request_obj) { 
    if (request_obj.num_people_logged_in) { 
     updateDOM(request_obj.num_people_logged_in); 
    } 
} 

function updateDOM(num_people_logged_in) { 
    if (num_people_logged_in) { 
     $("#mydiv > p.update").html("The updated value is: " + num_people_logged_in); 
    } 
} 

var timeoutID = null; 

// setup our timer, to periodically make an 
// AJAX call 
function init() { 
    timeOutID = setInterval(function(){ 
     getUpdate(); 
    },5000); 
} 

// stop the timer 
function cleanup() { 
    clearTimeout(timeoutID); 
} 

INDEX.HTML

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset='utf-8'> 
    <title>AJAX practice</title> 

    <!-- <link href="mycss.css" rel='stylesheet'> if needed --> 

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

     $(document).ready(function() { 

      init(); 

      $("#cleanup").on("click",function(){ 
       cleanup(); 
      }); 

     }); // end ready 

    </script> 
</head> 

<body> 

    <div id='mydiv'> 
     <p> 
      How many people are online? 
     </p> 
     <p class='update'> 
     </p> 
    </div> 

    <button id='cleanup'>Stop updating!</button> 

</div> 
</body> 
</html>