ajax--xhr属性方法&post实例

来源:互联网 发布:lorenz ectd注册软件 编辑:程序博客网 时间:2024/05/22 06:44


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" onsubmit="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=newActiveXObject('Microsoft.XMLHTTP');}return xhr;}// 创造xhrvar 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;}





0 0
原创粉丝点击