我制作了一个 JavaScript 类来简化 Ajax 请求。
我的课 :
var ajax =
{
method:"GET",
action:"",
data : "",
result: "",
setResult : function(re){this.result = re;},
setMethod : function(method){this.method = method.toUpperCase();},
setAction : function(page){this.action = page;},
addData : function(name,value){data_for_setting_data = name+"="+value+"&";this.data += data_for_setting_data;},
send : function()
{
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest)
XMLHttpRequestObject = new XMLHttpRequest();
else if(window.ActiveXObject)
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
else
{
try
{
XMLHttpRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
return false;
}
}
if(XMLHttpRequestObject)
{
var resulter;
datalength = this.data.length;
datasender = this.data.substr(0,datalength-1);
switch(this.method)
{
case "GET" :
XMLHttpRequestObject.open("GET",this.action+"?"+datasender,true);
XMLHttpRequestObject.onreadystatechange = function()
{
if(XMLHttpRequestObject.readyState == 4)
{
this.result = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
;
break;
case "POST" :
XMLHttpRequestObject.open("POST",this.action,true);
XMLHttpRequestObject.setRequestHeader("Content-type","application/x-www-form-urlencoded");
XMLHttpRequestObject.send(datasender);
XMLHttpRequestObject.onreadystatechange = function()
{
if(XMLHttpRequestObject.readyState == 4)
{
this.result = XMLHttpRequestObject.responseText;
}
}
;break;
}
}
}
}
当我发送这样的数据时:
ajax.setAction("a.php");
ajax.setMethod("get");
ajax.addData("myname","mohsen");
ajax.send();
alert(ajax.result);
结果将一事无成。
但例如,在第 44 行,如果我使用
alert(XMLHttpRequestObject.responseText)
代替
this.result = XMLHttpRequestObject.responseText;
它会正常工作。
我应该怎么做才能解决这个问题?
还有一个问题:它会降低加载速度吗?