现在的位置: 首页 > 综合 > 正文

ajax 实例-ajax 实例教程-php ajax 实例代码

2013年11月19日 ⁄ 综合 ⁄ 共 2387字 ⁄ 字号 评论关闭

HTML页面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<meta http-equiv="Content-Language" content="zh-cn" />
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta name="robots" content="all" />
<title>AJAX演示 </title>
<meta name="keywords" content="AJAX演示,AJAX,无刷新" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<script language="javascript">
function initxmlhttp()
{
var xmlhttp
try {
    xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e) {
     try {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     } catch (E) {
        xmlhttp=false;
     }
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
   try {
   xmlhttp = new XMLHttpRequest();
} catch (e) {
   xmlhttp=false;
}
}
if (!xmlhttp && window.createRequest) {
try {
   xmlhttp = window.createRequest();
} catch (e) {
   xmlhttp=false;
}
}
return xmlhttp;
}

function readcontent()
{
var xmlhttp=initxmlhttp();
var showcontent=document.getElementById("message");
var url="readfile.php";
xmlhttp.open("GET",url,true);
xmlhttp.setRequestHeader("Cache-Control","no-cache");
xmlhttp.onreadystatechange=function(){
     if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
     showcontent.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
function writecontent()
{
var xmlhttp=initxmlhttp();
var content=document.forms[0].content.value;
var url="writefile.php";
var poststr="content="+content;

xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send(poststr);
}
</script>
<body>
<div id="header">AJAX演示——操作文本文件</div>
<div id="des">
对文本文件执行写入,读取的基本操作。该程序主要用于测试,演示AJAX的POST和GET两种基本方式。
程序在win xp+php5.1+apache下通过测试。(注意writefile.php必须在php5.1下执行,其他的情况请自行些代码^_^)
</div>

<div id="mainform">
<form>
<textarea name="content" cols="50" rows="10" id="content">
</textarea>
<br>
<input type="button" name="Submit" value="读取文本文件数据" onClick="readcontent()">
<input type="button" name="Submit2" value="将数据写入文本文件" onClick="writecontent()"><br>
</form>
</div>
<div>文本文件的内容</div>
<div id="message" align="left" >

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

readfile.php

<?
header ("Cache-Control: no-cache, must-revalidate");
header('Content-Type:text/html;charset=GB2312');
$ok = "1"+"99998";
$author = $_GET['dzs_author'];
echo file_get_contents("test.txt")."<br/>";
echo $ok."<br/>";
echo $author."<br/>";
?>

writefile.php

<?
file_put_contents('test.txt',nl2br($_POST['content']));
echo $_POST['content'];
?>

建立text.txt

抱歉!评论已关闭.