我正在尝试使此函数正常工作,该函数对参数url进行请求,然后将responseText发送给callback该函数。
url
callback
似乎只能做到readyState 1(由于Firebug命令)。
readyState 1
这里是:
function Request(url, callback){ if (window.XMLHttpRequest) { // Mozilla, Safari, ... httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } else{ return false; } httpRequest.onreadystatechange = function(){ console.log(httpRequest.readyState); if (httpRequest.readyState == 4) { callback(httpRequest.responseText); } }; console.log(httpRequest, url); httpRequest.open('GET', url, true); httpRequest.send(null); }
我解决了分配onload事件而不是onreadystatechange的问题:
function Request(url, callback){ if (window.XMLHttpRequest) { // Mozilla, Safari, ... httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } else{ return false; } var readyStateChange = function(){ console.log(httpRequest.readyState); if (httpRequest.readyState == 4) { callback(httpRequest.responseText); } }; if (isFirefox && firefoxVersion > 3) { httpRequest.onload = readyStateChange; } else { httpRequest.onreadystatechange = readyStateChange; } console.log(httpRequest, url); httpRequest.open('GET', url, true); httpRequest.send(null); }