模仿prototype的ajax精简封装

本文介绍了一种基于prototype.js的问题解决方案:通过自定义一个简单的AJAX封装来避免内存溢出问题,并确保跨浏览器兼容性。提供了具体的实现代码及示例。

前段时间做项目使用了prototype.js后来发现一些复杂的情况,有时会有内存溢出的情况,索性干脆不用了,为了保证程序的兼容性,按prototype的接口实现了一个简单的ajax封装,火狐下没有测试.代码没格式化主要是想压缩行数.

 

<html>
    
<head>
        
<script> 
            
var syj={};
            
//发送ajax请求的方法
            syj.Ajax=function(url,obj){
                
var httpRequest;
                
if (window.ActiveXObject)try{httpRequest = new ActiveXObject("Microsoft.XMLHTTP");}catch (e){try{httpRequest = new ActiveXObject("Msxml2.XMLHTTP");}catch (e){}}
                
if (!httpRequest){alert('不能创建XMLHTTP实例');obj.onComplete();}
                httpRequest.onreadystatechange 
= function(){if (httpRequest.readyState == 4){obj['onComplete'](httpRequest);}}
                
if(url.indexOf('machineDate')==-1) url+=(url.indexOf('?')==-1?"?":"&")+("machineDate="+new Date().getTime());
                url
+=(url.indexOf('?')==-1?"?":"&")+obj.parameters;
                
if(obj.asynchronous==true) httpRequest.open(obj.method, url); else httpRequest.open(obj.method, url,false);
                httpRequest.send(
null);
                
return httpRequest;
            };
            
function test(){
                alert(
"test start ");
                
var url="http://www.baidu.com/";

                syj.Ajax(url,{
                                method  : 
"GET",
                                parameters : 
"s?wd=csdn",
                                asynchronous : 
true,
                                onFailure : 
function(httpRequest){
                                                    alert(
"出错了!");
                                               },
                                onComplete  : 
function(httpRequest){
                                                        
if(httpRequest.status==200){
                                                            alert(httpRequest.responseText);
                                                        }
                                                     }
                                 }
                            );
                alert(
"test end ");
            }
         
</script>
    
</head>
    
<body>
            
<input type="button" onclick="test()" value="测试" />
    
</body>
</html>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值