您的位置:首页 > 运维架构

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

2016-07-08 16:22 393 查看
一: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如下代码

<?php
header('content-type:text/html;charset="utf-8"');
error_reporting(0);

$username = $_GET['username'];
$pwd = $_GET['pwd'];

echo "账号:{$username},密码:{$pwd}";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ajax 服务器