xmlhttp的onreadystatechange为什么在send前面

    xiaoxiao2021-04-13  31

    在使用ajax向服务器发送请求的时候,由于粗心没有在意xmlHttp.onreadystatechange和xmlHttp.send的书写顺序,我把xmlHttp.send();写在xmlHttp.onreadystatechange的前面,开始并没有出现任何问题。直到使用IE7调试web前端样式的时候,才发现ajax无法得到正常的结果。最终找到问题的原因是xmlhttp的onreadystatechange需要要放在send前面,这样才稳定。 使用ajax发送请求一般的操作顺序是 先 open(... 然后赋值 onreadystatechange = func 最后 send open()只是初始化,做好准备发送, send()才是发送请求。 onreadystatechange是告诉xmlhttp当它的state发生改变的时候执行 readyState在生成xmlHttp时为0, 在 XMLHttpRequest.open时即改变,oepn会触发onreadystatechange事件的。 oepn放在onreadystatechange之前,会比放在onreadystatechange之后少执行一次onreadystatechange事件。 readyState 属性存有服务器响应的状态信息。每当 readyState 改变时,onreadystatechange 函数就会被执行。 下面是 readyState 属性可能的值: 状态 描述  0    请求未初始化(在调用 open() 之前)  1    请求已提出(调用 send() 之前)  2    请求已发送(这里通常可以从响应得到内容头部)  3    请求处理中(响应中通常有部分数据可用,但是服务器还没有完成响应)  4    请求已完成(可以访问服务器响应并使用它) 我们可以在onreadystatechange 函数中加一个if来判断请求是否成功,通过xmlHttp.responseText取得服务器返回的数据,如: if( xmlHttp.readyState == 4  && xmlHttp.status == 200 ) 通过上述可知,xmlhttp的onreadystatechange要放在send前面是为了给xmlHttp的readyState变化绑定一个监听事件。 from: http://www.pewees.com/article/1459999454489NkiGsztTkdD4hSWpkMD7i25Pk6.html

    转载请注明原文地址: https://ju.6miu.com/read-668664.html

    最新回复(0)