ajax的封装

本文深入讲解了AJAX的封装方法,包括GET和POST请求的处理,数据类型转换,以及异步和同步请求的管理。提供了实用的代码示例,帮助读者理解如何在实际项目中使用AJAX。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ajax的封装

function getParam(obj){
  "use strict";
  let str="";   
  for(var k in obj){
    str+=k+"="+obj[k]+"&";  
 }
  return str.substring(0,str.length-1);
}

function createXHR(){
   if(window.XMLHttpRequest){
     return new XMLHttpRequest();
  }
    return new ActiveXObject("Msxml2.XMLHTTP");
}



function Ajax(opts){
  opts.type=opts.type==undefined ? "get":opts.type;
  opts.async=opts.async==undefined ? true:opts.async;
  opts.dataType=opts.dateType==undefined ? "json":opts.dataType;
  
 let xhr=createXHR();
 if(opts.type=="get"){
   xhr.open("get",opts.url+"?"+getParam(opts.data),opts.async);
   xhr.send(null); 
 }else{
   xhr.open("post",opts.url,opts.async);
   xhr.setRequestHeader('Content-Type','application/x-www-form-urlencodeed');
   xhr.send(getParam(opts.data));
 }

 if(opts.async){
   xhr.onreadystatechange=function(){
    if(xhr.readyState==4){
      result();
    } 
  } 
 }else{
   result(); 
 }

}

function result(){
  if(xhr.status===200){
    if(opts.dataType=="json"){
      opts.success(JSON.parse(xhr.responseText));
   }else{
      opts.success(xhr.responseText);
   }
 }

}

 

转载于:https://www.cnblogs.com/xxcnhj/p/11024989.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值