查看: 320|回复: 0

[文章教程] 原生方式AJAX请求与JQ方式的AJAX请求示范

[复制链接]
xuanxiao 发表于 2022-5-3 11:29:19 | 显示全部楼层 |阅读模式
原生方式有更好的兼容性,对于早期IE和现代浏览器都能有好支持。

  1. function ajax() {

  2.         //创建核心对象

  3.         xhr = null;

  4.         if (window.XMLHttpRequest) {// 新版本的浏览器可以直接创建XMLHttpRequest对象

  5.             xhr = new XMLHttpRequest();

  6.         } else if (window.ActiveXObject) {// IE5或IE6没有XMLHttpRequest对象

  7.             xhr = new ActiveXObject("Microsoft.XMLHTTP");

  8.         }

  9.         //编写回调函数

  10.         xhr.onreadystatechange = function() {

  11.             if (xhr.readyState == 4 && xhr.status == 200) {

  12.                 //alert(xhr.responseText)
  13.                                 var result=xhr.responseText;
  14.                                 result=result.slice(0,result.length-1)                       
  15.                         var arr=result.split(",")
  16.                         var obj;               
  17.                         var j;         
  18.                         for(j = 0,len=arr.length; j < len; j++)  {
  19.                                   obj= document.getElementById("day_"+arr[j]);
  20.                                        
  21.                                        
  22.                                   
  23.                                   if (obj) {
  24.                     obj.className +='ttasp';       
  25.                  //console.log(obj);
  26.                   }

  27.                                 }
  28.                                

  29.             }

  30.         }

  31.         //open设置请求方式和请求路径

  32.         xhr.open("get", "../ttasp/action.asp");//一个url还传递了数据,后面还可以写是否同步

  33.         //send 发送

  34.         xhr.send();

  35.     }
  36.        
  37.         ajax();
复制代码


下面是JQ方式:
  1. $.ajax({
  2.   type: "GET",
  3.   url: "../ttasp/action.asp",
  4.   data: {   
  5.     act: "qd"
  6.   },
  7.   success:function(result){
  8.                         //$("#div1").html(result);
  9.                         result=result.slice(0,result.length-1)                       
  10.                         var arr=result.split(",")
  11.                         var obj;                         
  12.                         for (const elem of arr) {
  13.                                     obj= $("#day_"+elem);
  14.                                         console.log(obj);
  15.                                         //obj.setAttribute("style","background-image:url(../ttasp/bg.jpg);background-repeat:no-repeat; background-size:100% 100%;  -moz-background-size:100% 100%;")
  16.                                   obj.addClass('ttasp');

  17.                                 }
  18.                 }
  19. });
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表

在线客服

售前咨询
售后咨询
服务热线
023-58418553
微信公众号