xhr的属性和方法列表
xhr.onreadystatechange = function(){
/*var pg = document.getElementById('zt');
pg.innerHTML=pg.innerHTML + '状态现在变成' + this.readyState + '<br/>';*/
if(this.readyState == 4){
var pg = document.getElementById('zt');
var str = '';
str = str + "状态码是" + this.status + '<br/>';
str = str + "状态文字" + this.statusText + '<br/>';
str = str + "头信息里的" + this.getResponseHeader('Content-Length') + '<br/>';
str = str + "取所有头信息" + this.getAllResponseHeaders();
pg.innerHTML = str;
}
}
效果图如下
post方法
网页是填写2个并提交的页面
<!-- 如果onsubmit里的方法没有得到true就会不执行action -->
<form action="./3post.php" method="post" target="regzone" οnsubmit="return post();">
用户名<input type="text" name="username" />
密码<input type="text" name="password" />
<input type="submit" value="提交">
</form>
<iframe name='regzone' width="0" height="0" frameborder="0"></iframe>
js里这些原封不动
<script type="text/javascript">
function createXHR(){
var xhr = null;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else if(window.ActiveXObject){
xhr=new ActiveXObject('Microsoft.XMLHTTP');
}
return xhr;
}
// 创造xhr
var xhr=createXHR();
下面post主要改变如下
1接受post数据
2请求头添加 type
3send post 数据
function post(){
// 获得post来的数据 username
var un=document.getElementsByName('username')[0].value;
var pw=document.getElementsByName('password')[0].value;
// 打开连接
xhr.open('POST','./3post.php',true);
// 建议这边就绑定
xhr.onreadystatechange = function(){
if (this.readyState == 4) {
alert(this.responseText);
}
}
// 因为是post所以是 这个 一定要
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// 发送请求,这里开始和get不一样了,post需要发送表单填写的
xhr.send('username='+un+'&password='+pw);
// 有这个就不会action到那里去了
return false;
}