使用Ajax请求数据

1. 请求文本类型的数据(jQuery方法)

 $("button").on("click",function(){
    jQuery.ajax({
         type : "get",//默认为get请求
         url : "http://localhost:9999/01.txt", //请求的地址
         dataType : "text", // 请求文本类型数据
         success : function(data){
             console.log(data) //返回响应数据
         },
         error :function(err){
             console.log(err)//返回为错误对象,其中会包含错误信息
         }
     })
 })

在这里插入图片描述

2. 请求json类型数据(jQuery方法)

 $("button").on("click",function(){
    jQuery.ajax({
         type : "get",//默认为get请求
         url : "http://localhost:9999/01.json", //请求的地址
         dataType : "json", // 请求文本类型数据
         success : function(data){
             console.log(data) //返回响应数据
         },
         error :function(err){
             console.log(err)//返回为错误对象,其中会包含错误信息
         }
     })
 })

在这里插入图片描述

3. 延时请求

   if(window.XMLHttpRequest){
     	var xhr = new XMLHttpRequest() //普通浏览器
   }else{
        var xhr = new ActiveXObject()  //兼容老版本IE浏览器
   }
   if(xhr.readyState == 4){  //状态码为4 服务器数据已经完全接收,或者本次接收已经失败了
      if(xhr.status == 200){  // 响应码为200 访问正常
          console.log(xhr.responseText)
      }
   }
   xhr.timeout = 5000;		//5秒后,请求超时后,停止请求
   xhr.ontimeout = function(){
       console.log("请求超时,请稍后再试")
   }
   xhr.open("get","03.php",true) //建立连接
   xhr.send() //发送HTTP请求

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值