簡體   English   中英

是否可以將JS腳本放在PHP文件中?

[英]Is it possible to put JS scripts in PHP File?

<?php

mysql_connect('localhost','root','');
mysql_select_db('ditwhales');

$studno=$_POST['studno'];

$command=mysql_query("SELECT * FROM chat WHERE studno= 

'$studno'");
$numrs=mysql_num_rows($command);

if ($numrs==0){
print 'Sorry but you are not one of the Whales. Please contact the web 

master and ask for registration of your Student No. Thank you!';
}

else{
$all=mysql_query("SELECT * FROM msgs");

while ($row=mysql_fetch_array($all)){

echo $row['message'] . "<br />";

};
}




?>

我有這個代碼。 但問題是我希望其他人每1秒刷新一次。 這甚至可能嗎? 我認為返回功能可以工作,但我不知道如何使用它。 有人可以幫忙嗎?

你可以每1秒用javascript ajax加載php文件,也可以使用無限循環並放入睡眠(1); 每1秒刷新一次

正如Mohammad建議的那樣,您可以使用客戶端腳本來解決此問題,在服務器上調用php文件並返回答案,例如:

<script type="text/javascript">
function callphp(){
    setTimeout('callphp()', 1000);
    xmlhttp = null;
    count = 0;
    var d = new Date();
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{
        // IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
RndString = d.getFullYear() + "" + d.getMonth() + "" + d.getDate() + ""  + d.getHours() + "" + d.getMinutes() + "" + d.getSeconds() + "" + count++;
    xmlhttp.open("GET",'file.php?C=' + RndString,false);
    xmlhttp.send(null);
    if(xmlhttp.responseText != ""){
        document.getElementById("div").innerHTML = xmlhttp.responseText;
        }
}
</script>

請檢查一下,讓我們知道發生了什么。

你有點混亂的角色:php運行服務器端,它將你顯示的數據返回給客戶端,通常是瀏覽器直接顯示的完整HTML,但它也可以返回各種格式的數據,如jsonXML它作為RPC的提供者,這是一種通過php文件端點調用函數並讓它返回數據的奇特方式。

如果您想操縱客戶端(通常是webbrowser)與用戶交互的方式,那么您將需要編寫在該特定上下文中交互的代碼,為瀏覽器執行此操作的統一方法是使用JavaScript

使用javascript,您可以通過多種方式激活頁面(inter),例如使用setInterval每隔X秒調用一次例程。

var cMR;

function callMyResults(){
}

window.onload = function(){
    cMR = setInterval('callMyResults',5000);
}
;

為了在加載頁面時自動調用你的代碼,我們將一個函數附加到onLoad事件處理程序,這將執行分配給它的函數中的所有內容,在我們的例子中,它將設置一個5000毫秒的時間間隔,它將執行每次都有CallMyResults()函數。 setInterval的結果保存在cMR全局中,以便以后可以在需要時用於停止在間隔上執行的代碼。

所以目前這段代碼什么也沒做。 Javascript可以調用其他頁面,從而通過統一稱為AJAX的東西檢索數據最初這是為了檢索您隨后執行的XML文檔(或者只是簡單地寫入當前顯示的文檔)。 后來這已經演變為使用json,因為它返回一個javascript原生元素,使其更容易使用,並且通常更小的尺寸來通過網絡連接進行傳輸,這使得頁面更加快捷。

存在許多庫可以輕松地完成此操作,其中最流行的是jquery ,但您也可以使用XMLHttpRequest對象(AJAX的基礎)編寫自己的調用。 你會在網上找到很多這樣的例子,比如這個用於檢索json數據的例子。

一般來說,建議您使用已建立的庫,以便於使用,您自己的理智,以及更好,更容易訪問的編碼。

最后在PHP方面,您只需像往常一樣收集數據,但是打印方式有點不同,可以是您自己指定格式的XML,也可以使用json_encode將其作為json返回。 這可以簡單如下:

<?php
$pdo = new PDO('mysql:dbname=testdb;host=127.0.0.1',$user,$password);
$result = $pdo->query('SELECT * FROM msgs');
print json_encode($result->fetchAll());

請注意,我已經使用PHP數據對象 (通常稱為PDO)來訪問數據庫,這提供了一種訪問數據庫的統一方式,以防您切換到另一個RDBMS而不是當前使用的數據庫 (mysql)。 在這種情況下,您需要適應的是您在實例化時為PDO對象提供的DSN字符串。 PDO的另一個非常大的好處是,它可以保護您免受SQL注入通過提供方法來輕松地創建一個事先准備好的聲明 ,以您所提供的參數會被自動引用(從而保護); 不再推薦使用mysql_ *系列函數:eithr使用PDO或使用mysqli。

那么,給你一個工作的例子:

我們有1個客戶端頁面:display.html和2個用於生成和返回數據的服務器端頁面(fillList.php和retrieveList.php)

fillList.php

<?php
    // we work with the following table
// create table list_data (`when` DATETIME NOT NULL);

    // make sure to adapt these settings to yours, including username and password
$pdo = new PDO('mysql:dbname=scratch;host=localhost','username','password');
$pdo->exec('INSERT INTO list_data VALUES (NOW())');

這將在list_data表的when列中插入一個新值

retrieveList.php

<?php
    // make sure to adapt these settings to yours, including username and password
    $pdo = new PDO('mysql:dbname=scratch;host=localhost','scratch','scratch');
    print json_encode($pdo->query('SELECT `when` FROM list_data 
                                   ORDER BY `when` DESC'
                                  )->fetchAll(PDO::FETCH_ASSOC)
                      );

檢索list_data表中按降序排序的所有值,並將生成的關聯數組作為json對象返回。

我決定使用jquery向您展示示例客戶端頁面,確保下載最新的jquery-1.7.2.js並將其放在與此文件相同的目錄中。

display.html

<html><head><title>Refreshing List</title>
<script src="http://localhost/jquery-1.7.2.js" />
</head>
<body>

<p>this list refreshes every 5 seconds, a new value is inserted every 2 seconds</p>
<ul id="toRefresh">
<li>base</li>
</ul>
<script>

function fillList(){
  // we insert a new value in the database by calling fillList.php
  $.get("http://localhost/fillList.php");
}

function refreshList(){
  /* 
    we retrieve the json encoded data returned by retrieveList.php 
    and process it in our anonymous function
  */
  $.getJSON("http://localhost/retrieveList.php",function (data){
    var items = [];
// loop through the returned array
    $.each(data,function(key,val){
      // we passed an associative array so we can use the columnname: 'when'
      items.push("<li>when: " + val['when'] + "</li>");
});
    // clear the list and append the data to it
$("#toRefresh").empty();
$("#toRefresh").append(items.join(''));
  });
}

// jquery uses .ready() instead of window.onload = function(){}
$(document).ready(function (){
  // retrieve the data every 5 seconds
  setInterval(function(){refreshList();},5000);
  // insert additional new data every 2 seconds
  setInterval(function(){fillList();},2000);

  // we fill the list with its initial values
  refreshList();

});
</script>
</body>
</html>

正如您所看到的,jquery為您提供了一種簡單的方法來執行這些操作。 運行display.html頁面,您將看到一個不斷增長且令人耳目一新的mysql日期時間值列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM