zoukankan      html  css  js  c++  java
  • Ajax基础(下)


    1
    <script type="text/javascript"> 2 // var a=1; 3 // alert(window.a); 4 // a属于window下的一个属性 5 /*function show() 6 { 7 alert('a') 8 }; 9 window.show()*/ 10 //alert(a)----会出错和alert(window.a)----结果是undefined;的区别 11 </script>
     1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     2 <html xmlns="http://www.w3.org/1999/xhtml">
     3 <head>
     4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     5 <title>无标题文档</title>
     6 <script>
     7 window.onload=function ()
     8 {
     9     var oBtn=document.getElementById('btn1');
    10     
    11     oBtn.onclick=function ()
    12     {
    13         //1.创建ajax对象
    14         //IE6以上
    15         /*var oAjax=new XMLHttpRequest();
    16         
    17         alert(oAjax);*/
    18         
    19         //IE6
    20         /*var oAjax=new ActiveXObject("Microsoft.XMLHTTP");
    21         
    22         alert(oAjax);*/
    23         var oAjax=null;
    24         
    25         if(window.XMLHttpRequest)
    26         {
    27             oAjax=new XMLHttpRequest();//兼容火狐,谷歌浏览器
    28         }
    29         else
    30         {
    31             oAjax=new ActiveXObject("Microsoft.XMLHTTP");//IE自带的控件
    32         }
    33         
    34         //2.连接服务器
    35         //open(方法, url, 是否异步)get和post方法的选择需要和后台需求来定;文件的地址;绝大多数都是异步传输,这样可以同时做多件事情。
    36         oAjax.open('GET', 'abc.txt', true);
    37         
    38         //3.发送请求
    39         oAjax.send();
    40         
    41         //4.接收返回
    42         //OnReadyStateChange
    43         oAjax.onreadystatechange=function ()
    44         {
    45             if(oAjax.readyState==4)//4表示完成
    46             {
    47                 if(oAjax.status==200)//表示成功
    48                 {
    49                     alert('成功:'+oAjax.responseText);//返回文本内容
    50                 }
    51                 else
    52                 {
    53                     alert('失败');
    54                 }
    55             }
    56         };
    57     };
    58 };
    59 </script>
    60 </head>
    61 
    62 <body>
    63 <input id="btn1" type="button" value="读取文件" />
    64 </body>
    65 </html>

    请求状态监控 onreadystatechange事件

    readyState属性:

    请求状态

    0 (未初始化)还没有调用open()方法

    1 (载入)已调用send()方法,正在发送请求

    2 (载入完成)send()方法完成,已收到全部响应内容

    3 (解析)正在解析响应内容

    4 (完成)响应内容解析完成,可以在客户端调用了

    status属性:请求结果。成功的话会返回

    responseText返回文件的内容200,失败会弹出404等数字。

  • 相关阅读:
    alpine下ruby安装sass compass报 Error installing compass 错误的解决方案
    Andoid项目中增加openCV的依赖
    appium教程_4.adb常用命令
    appium教程_2.概念加深
    appium教程_1.基础概念认知
    windows下查看进程(进阶)
    linux下安装google-chrome浏览器和chromedriver
    钉钉内网穿透windows启动命令
    Docker
    HTTP协议
  • 原文地址:https://www.cnblogs.com/paxster/p/3100179.html
Copyright © 2011-2022 走看看