用原生JS&PHP简单的AJAX实例
功能介绍:
1)file.html 使用 xmlhttp 请求服务器端文件 text ,并更新 file.html 的部分内容
2)update.html 使用 xmlhttp 通过 filewrite.php 更改服务器端文件 text 的内容
3)filewrite.php 接收 update.html 中 xmlhttp 提交的数据更新 text 内容
file.html
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <title>ajax</title> <style> body { background:whitesmoke; } * { margin: 0 0 0 0; padding: 0 0 0 0; } .header { height:100px; width:100%; text-align: center; font-size: 80px; color:gray; } .container { text-align: center; } .ipttag { display: inline-block; width:100px; color: brown; } #responseContent { color : rgb(20, 104, 214); } </style> </head> <body> <div class="header">FILE Learning</div> <div class="container"> <form> <input type='button' value='获取text内容' id="submit"/> <p id="responseContent"></p> </form> </div> </body> <script> document.getElementById('submit').onclick = function() { //id = document.getElementById('id').value; //passwd = document.getElementById('passwd').value; var xmlhttp; xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) { //alert(xmlhttp.responseText); document.getElementById('responseContent').innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "./text", true); xmlhttp.send(); } //document.getElementById('submit').onclick = showHints; //document.getElementById('id').onkeyup = showHints; </script> </html>
update.html
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <title>UPDATE</title> <style> body { background:whitesmoke; } * { margin: 0 0 0 0; padding: 0 0 0 0; } .header { height:100px; width:100%; text-align: center; font-size: 80px; color:gray; } .container { text-align: center; } #responseContent { color : rgb(20, 104, 214); } .text { width : 500px; height: 300px; text-align: left; } </style> </head> <body> <div class='header'>FILE Learing</div> <div class='container'> <textarea class='text' type="area" id='text'></textarea> <br> <input type='button' value='更新text内容' id='updateButton'> <p id="responseContent"></p> </div> </body> <script> document.getElementById('updateButton').onclick = function () { var text = document.getElementById('text').value; var postContent = 'text=' + text; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //document.getElementById('responseContent').innerHTML = "更新成功"; alert('更新成功'); } } xmlhttp.open('POST', './filewrite.php', true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send(postContent); } </script> </html>
filewrite.php
<?php $text = $_POST['text']; $file = fopen('./text', 'w') or exit('无法打开文件'); fwrite($file, $text); fclose($file); ?>