ajax,php文件读取

 

大道至简-20%的功能满足80%的需求

1、php文件读取

fopen()

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

fread()

fread() 函数读取打开的文件。
fread() 的第一个参数包含待读取文件的文件名,第二个参数规定待读取的最大字节数。
如下 PHP 代码把 "webdictionary.txt" 文件读至结尾:

fread($myfile,filesize("webdictionary.txt"));

fclose()

fclose() 函数用于关闭打开的文件。

注释:用完文件后把它们全部关闭是一个良好的编程习惯。您并不想打开的文件占用您的服务器资源。

fclose() 需要待关闭文件的名称(或者存有文件名的变量):

<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>

PHP 读取单行文件 - fgets()

fgets() 函数用于从文件读取单行。
下例输出 "webdictionary.txt" 文件的首行:

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
注释:调用 fgets() 函数之后,文件指针会移动到下一行。

PHP 检查 End-Of-File - feof()

feof() 函数检查是否已到达 "end-of-file" (EOF)。
feof() 对于遍历未知长度的数据很有用。
下例逐行读取 "webdictionary.txt" 文件,直到 end-of-file:

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// 输出单行直到 end-of-file
while(!feof($myfile)) {
  echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>

PHP 读取单字符 - fgetc()

fgetc() 函数用于从文件中读取单个字符。
下例逐字符读取 "webdictionary.txt" 文件,直到 end-of-file:

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// 输出单字符直到 end-of-file
while(!feof($myfile)) {
  echo fgetc($myfile);
}
fclose($myfile);
?>
注释:在调用 fgetc() 函数之后,文件指针会移动到下一个字符。

2、AJAX

创建 XMLHttpRequest 对象

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

向服务器发送请求

如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:

xmlhttp.open("GET","count.php",true);
xmlhttp.send();

原文链接

服务器响应

如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。

onreadystatechange 事件


在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。
当 readyState 等于 4 且状态为 200 时,表示响应已就绪:

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}
注释:onreadystatechange 事件被触发 5 次(0 - 4),对应着 readyState 的每个变化。

使用 Callback 函数

callback 函数是一种以参数形式传递给另一个函数的函数。
如果您的网站上存在多个 AJAX 任务,那么您应该为创建 XMLHttpRequest 对象编写一个标准的函数,并为每个 AJAX 任务调用该函数。
该函数调用应该包含 URL 以及发生 onreadystatechange 事件时执行的任务(每次调用可能不尽相同):

function myFunction()
{
loadXMLDoc("ajax_info.txt",function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  });
}
原文地址:https://www.cnblogs.com/xyws/p/5336276.html