zoukankan      html  css  js  c++  java
  • xmlHttpRequest对象的使用

     创建:

       function createXmlHttpRequest()

    {

    var xmlrequest;

           if (window.ActiveXObject)

    {    

               xmlrequest = new ActiveXObject("Microsoft.XMLHTTP");    

           }          

     else {          

         xmlrequest = new XMLHttpRequest();      

         }

    return xmlrequest;

    }

    请求:

    1:get

    xmlhttp.open("GET","test1.txt",true);//语法:open(method,url,async)

    //method:请求的类型;GET 或 POST

  • //url:文件在服务器上的位置
  • //async:true(异步)或 false(同步)

  • xmlhttp.send();

    使用get时候会出现缓存,可以如下解决:

    为了避免这种情况,请向 URL 添加一个唯一的 ID:

    xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
    xmlhttp.send();
    
    2:post

    简单的post:

    xmlhttp.open("POST","demo_post.asp",true);
    xmlhttp.send();
    如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:

    xmlhttp.open("POST","ajax_test.asp",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("fname=Bill&lname=Gates");

    onreadystatechange 事件

     1、onreadystatechange   

     存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。

    2、readyState   

    存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

    • 0: 请求未初始化
    • 1: 服务器连接已建立
    • 2: 请求已接收
    • 3: 请求处理中
    • 4: 请求已完成,且响应已就绪

    3、status

    200: "OK"

    404: 未找到页面

    4、就绪

    当 readyState 等于 4 且状态为 200 时,表示响应已就绪:

    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
      }

    响应:

    如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。

    1、responseText 获得字符串形式的响应数据。

    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

    2、responseXML 获得 XML 形式的响应数据。

    xmlDoc=xmlhttp.responseXML;
    txt="";
    x=xmlDoc.getElementsByTagName("ARTIST");
    for (i=0;i<x.length;i++)
    {
    txt=txt + x[i].childNodes[0].nodeValue + "<br />";
    }
    document.getElementById("myDiv").innerHTML=txt;

查看全文
  • 相关阅读:
    去 抚仙湖 和 去 洱海 差不多
    开源项目 D++
    未来 的 科学家, 不仅 是 数学家, 也是 系统设计 大师
    出一道 智商题 : 证明 永动机 是否 能 设计出来 ?
    评论一下 “推倒数学大厦”的 一个 作业题
    用 无穷级数 的 思路 三等分角
    三等分角 化圆为方 可以 考虑 用 无穷级数 的 方式 来 实现
    CPU 应该 搞 0 级 Cache , 而不是 大寄存器
    关于 智商 (2)
    关于 智商
  • 原文地址:https://www.cnblogs.com/mazhlo/p/2003989.html
  • Copyright © 2011-2022 走看看