AJAX教程系列二:open方法与数据获取与处理

来源:互联网 发布:koala for mac 编辑:程序博客网 时间:2024/05/19 19:42

一:open方法与服务器状态

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script>    window.onload = function() {        var oBtn = document.getElementById('btn');          oBtn.onclick = function() {            var xhr = null;            // 打开浏览器            try {                xhr = new XMLHttpRequest();            } catch (e) {                xhr = new ActiveXObject('Microsoft.XMLHTTP');            }            // 在地址栏输入地址            /*            open方法            是否异步                异步:非阻塞 前面的代码不会影响后面代码的执行                同步:阻塞 前面的代码会影响后面代码的执行            */            xhr.open('get','1.txt',true);            // 发送请求            xhr.send();            // 等待服务器返回内容            xhr.onreadystatechange = function() {                if(xhr.readyState == 4){                    if(xhr.status == 200){                        alert(xhr.responseText);                    }else {                        alert("错误"+xhr.status);                     }                }               }         }    }</script></head><body>    <input type="button" value="按钮" id="btn" /></body></html>

二:数据获取

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script>    window.onload = function() {        var oBtn = document.getElementById('btn');          oBtn.onclick = function() {            var xhr = null;            // 打开浏览器            try {                xhr = new XMLHttpRequest();            } catch (e) {                xhr = new ActiveXObject('Microsoft.XMLHTTP');            }            // 在地址栏输入地址            /*            缓存时在url?后加随机数,乱码encodeURI            */        xhr.open('get','1.php?username='+encodeURI('小胖子')+'&pwd=1111&' + new Date().getTime(),true);            // 发送请求            xhr.send();            // 等待服务器返回内容            xhr.onreadystatechange = function() {                if(xhr.readyState == 4){                    if(xhr.status == 200){                        alert(xhr.responseText);                    }else {                        alert("错误"+xhr.status);                     }                }               }         }    }</script></head><body>    <input type="button" value="按钮" id="btn" /></body></html>

1.php如下代码

<?phpheader('content-type:text/html;charset="utf-8"');error_reporting(0);$username = $_GET['username'];$pwd = $_GET['pwd'];echo "账号:{$username},密码:{$pwd}";
2 0
原创粉丝点击