您的位置:首页 > Web前端 > JavaScript

解决问题:onreadystatechange只触发一次

2016-10-29 10:01 489 查看
在研究最基本的AJAX - onreadystatechange 事件时,
通过
XMLHttpReq.onreadystatechange=processResponse();
绑定了处理 函数,但是仅仅在XMLHttpReq.readyState==1的时候触发了一次该函数?

先看下认识下onreadystatechange
onreadystatechange 事件
当请求被发送到服务器时,我们需要执行一些基于响应的任务。
每当 readyState 改变时,就会触发 onreadystatechange 事件。
readyState 属性存有 XMLHttpRequest 的状态信息。
下面是 XMLHttpRequest 对象的三个重要的属性:

属性描述
onreadystatechange存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
readyState存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

0: 请求未初始化

1: 服务器连接已建立

2: 请求已接收

3: 请求处理中

4: 请求已完成,且响应已就绪
status200: "OK"

404: 未找到页面
在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。
当 readyState 等于 4 且状态为 200 时,表示响应已就绪:
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
} }

解决方案,得到的解答是:在调用函数的时候不能带任何参数,使用()都不行!

错误示范:XMLHttpReq.onreadystatechange=processResponse();

正确示范;XMLHttpReq.onreadystatechange=processResponse;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息