需求
通过html页面的按钮,将页面中的某个输入框的值传递到服务器,数据经过处理后显示在输入框下方。
实现过程
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
function cl(){
var data = document.getElementById("in").value;
//创建XMLHttpRequest对象
var xhr = getHTTPObject();
//异步执行时根据处理状态执行的函数
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
//处理成功获取结果值
document.getElementById("show").innerHTML = "成功-数据:" + xhr.responseText;
}else if(xhr.status == 404){
document.getElementById("show").innerHTML = "找不到处理的页面";
}
else{
document.getElementById("show").innerHTML = "处理中";
}
}
//第三个参数代表async值,如果为true代表异步执行,false代表同步执行。
//同步执行会在请求过程中锁定浏览器。
xhr.open("POST","action.php",true);
//设置post提交请求头
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//放入post方式提交的数据
xhr.send("good=" + data +"&status=1");
}
//针对不同浏览器来获取XMLHttpRequest对象
function getHTTPObject() {
if(typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function() {
try{return new ActiveXObject("Msxml2.XMLHTTP.6.0");}
catch(e){}
try{return new ActiveXObject("Msxml2.XMLHTTP.3.0");}
catch(e){}
try{return new ActiveXObject("Msxml2.XMLHTTP");}
catch(e){}
return false;
}
return new XMLHttpRequest();
}
</script>
</head>
<body>
<input type="text" name="good" id="in">
<button onclick="cl();">click me</button>
<div id="show"></div>
</body>
</html>
如果要用GET方式提交的话,将以下代码置入替换
xhr.open("GET","action.php?good="+data+"status=1",true);
xhr.send();
<?php
//让程序返回数据前休眠3s
sleep(3);
echo $_POST['good']."*状态为:".$_POST['status'];
?>
结果
XMLHttpRequest 中的readystate状态表
readystate | 描述 |
---|---|
0 | 请求未初始化 |
1 | 已建立服务器连接 |
2 | 请求已被服务器接收 |
3 | 正在处理中 |
4 | 处理完成,响应就绪 |