• Ajax请求


    // 表单提交 post
    function
    submitData(){   var xhr = createXHR();   xhr.onreadystatechange = function(){     if (xhr.readyState == 4){       if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){         alert(xhr.responseText);       } else {         alert("Request was unsuccessful: " + xhr.status);     }   } }; xhr.open("post", "postexample.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var form = document.getElementById("user-info");
    // send(string) 仅限于post方法
    xhr.send(serialize(form)); }

    1.创建XMLHttpRequest对象(简称XHR)

    // 创建构造函数
    function createXHR() {
          if (typeof XMLHttpRequest != "undefined") {
            return new XMLHttpRequest();
          } else if (typeof ActiveXObject != "undefined") {
            if (typeof arguments.callee.activeXString != "string") {
              var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"],
                i, len;
              for (var i = 0, len = versions.length; i < len; i++) {
                try {
                  new ActiveXObject(versions[i])
                  arguments.callee.activeXString = versions[i]
                  break
                } catch (ex) {
                  // nothing to do
                }
              }
    
            }
            return new ActiveXObject(arguments.callee.activeXString)
          } else {
            throw new Error("No XHR object avaiable.")
          }
        }
    // 创建实例
    var xhr = new createXHR()

    2.判断response状态

    在调用 open()之前指定 onreadystatechange
    事件处理程序才能确保跨浏览器兼容性

    xhr.onreadystatechange = function() {
          if (xhr.readystate == 4) {
            if (xhr.status >= 200 && xhr < 300 || xhr.status == 304) {
              alert(xhr.responseText)
            } else {
              alert("Request wa unsuccessful:" + xhr.status)
            }
          }
     }

    XHR 对象的 readyState 属性 :

    0:未初始化。尚未调用 open()方法。
    1:启动。已经调用 open()方法,但尚未调用 send()方法。
    2:发送。已经调用 send()方法,但尚未接收到响应。
    3:接收。已经接收到部分响应数据。
    4:完成。已经接收到全部响应数据,而且已经可以在客户端使用了


    响应数据:

    responseText:作为响应主体被返回的文本。
    responseXML:如果响应的内容类型是"text/xml""application/xml",这个属性中将保
    存包含着响应数据的 XML DOM 文档。
    status:响应的 HTTP 状态。 成功 200 
    statusTextHTTP 状态的说明。

    3.XHR的用法

      step1:调用 open()方法 open("methods", "url", Boolean)

        接受3个参数,请求类型(get/post),请求的URL,是否发送异步请求(true:异步;false: 同步)

    xhr.open("get", "example.php", false);

      3.1 HTTP头部信息:

       Accept:浏览器能够处理的内容类型。
       Accept-Charset:浏览器能够显示的字符集。
       Accept-Encoding:浏览器能够处理的压缩编码。
       Accept-Language:浏览器当前设置的语言。
       Connection:浏览器与服务器之间连接的类型。
       Cookie:当前页面设置的任何 Cookie
       Host:发出请求的页面所在的域 。
       Referer:发出请求的页面的 URI。注意, HTTP 规范将这个头部字段拼写错了,而为保证与规
      范一致,也只能将错就错了。(这个英文单词的正确拼法应该是 referrer。)
       User-Agent:浏览器的用户代理字符串。 

      3.2 GET 方法

      GET 是最常见的请求类型,最常用于向服务器查询某些信息。必要时,可以将查询字符串参数追加
      到 URL 的末尾,以便将信息发送给服务器。对 XHR 而言,位于传入 open()方法的 URL 末尾的查询字
      符串必须经过正确的编码才行

      查询字符串中每个参数的名称和值都必须使用 encodeURIComponent()进行编码
      然后才能放到 URL 的末尾;而且所有名-值对儿都必须由和号(&)分隔


    xhr.open("get", "example.php?name1=value1&name2=value2", true);
    function addURLParam(url, name, value) {
    url += (url.indexOf("?") == -1 ? "?" : "&");
    url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
    return url;
    }

      这个 addURLParam()函数接受三个参数:要添加参数的 URL、参数的名称和参数的值。这个函数
      首先检查 URL 是否包含问号(以确定是否已经有参数存在)。如果没有,就添加一个问号;否则,就添
      加一个和号。然后,将参数名称和值进行编码,再添加到 URL 的末尾。最后返回添加参数之后的 URL

    function submitData(){
      var xhr = createXHR();
      xhr.onreadystatechange = function(){
        if (xhr.readyState == 4){
          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
          alert(xhr.responseText);
        } else {
          alert("Request was unsuccessful: " + xhr.status);
        }
      }
    
    xhr.open("get", "example.php?name1=value1&name2=value2", true);
    // 设置请求头

    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    // 发送 
    xhr.send(null); }

      3.3 POST 方法

      POST 请求应该把数据作为请求的主体提交,主体数据格式不限

    xhr.open("post", "example.php", true);
    function submitData(){
      var xhr = createXHR();
      xhr.onreadystatechange = function(){
        if (xhr.readyState == 4){
          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
          alert(xhr.responseText);
        } else {
          alert("Request was unsuccessful: " + xhr.status);
        }
      }
    };
    xhr.open("post", "postexample.php", true);
    // 设置请求头 xhr.setRequestHeader(
    "Content-Type", "application/x-www-form-urlencoded");
    //表单提交
    var form = document.getElementById("user-info");
    // 发送 xhr.send(serialize(form)); }

      step2:设置请求头 setRequestHeader()

      参数1: 头部字段名称

      参数2:头部字段值

      要成功发送请求头部信息,必须在调用 open()方法之后且调用 send()方法之前调用setRequestHeader() 方法

      调用 XHR 对象的 getResponseHeader()方法并传入头部字段名称,可以取得相应的响应头部信
      息。而调用 getAllResponseHeaders()
    方法则可以取得一个包含所有头部信息的长字符串

      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

      step3:调用 send()方法

    补充1:

    服务器返回的 MIME 类型是 text/plain,但数据中实际包含的是 XML。根据 MIME 类型,
    即使数据是 XMLresponseXML 属性中仍然是 null。通过调用 overrideMimeType()方法,可以保
    证把响应当作 XML 而非纯文本来处理。
    XMLHttpRequest 2级 ,overrideMimeType()方法,用于重写 XHR 响应的 MIME
    类型。 

    var xhr = createXHR();
    xhr.open("get", "text.php", true);
    xhr.overrideMimeType("text/xml");
    xhr.send(null);

    补充2: 进度事件 ProgressEvents

    loadstart:在接收到响应数据的第一个字节时触发。
    progress:在接收响应期间持续不断地触发。
    error:在请求发生错误时触发。
    abort:在因为调用 abort()方法而终止连接时触发。
    load:在接收到完整的响应数据时触发。
    loadend:在通信完成或者触发 errorabort load 事件后触发。

    每个请求都从触发 loadstart 事件开始,接下来是一或多个 progress 事件,然后触发 error
    abort load 事件中的一个,最后以触发 loadend 事件结束。
    支持前 5 个事件的浏览器有 Firefox 3.5+Safari 4+ChromeiOS Safari Android WebKit
    Opera(从第 11 版开始)、 IE 8+只支持 load 事件。目前还没有浏览器支持 loadend 事件。


    load 事件

    用以替代 readystatechange 事件。响应接收完毕后将触发 load 事件,因此也就没有必
    要去检查 readyState 属性了

     

    var xhr = createXHR();
    xhr.onload = function(){
      if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
        alert(xhr.responseText);
      } else {
        alert("Request was unsuccessful: " + xhr.status);
      }
    };
    xhr.open("get", "altevents.php", true);
    xhr.send(null);

    progress 事件

    这个事件会在浏览器接收新数据期间周期
    性地触发。而 onprogress 事件处理程序会接收到一个 event 对象,其 target 属性是 XHR 对象,但
    包含着三个额外的属性: lengthComputableposition totalSize。其中, lengthComputable
    是一个表示进度信息是否可用的布尔值, position 表示已经接收的字节数, totalSize 表示根据
    Content-Length 响应头部确定的预期字节数。有了这些信息,我们就可以为用户创建一个进度指示器
    了。


    为确保正常执行, 必须在调用 open()方法之前添加 onprogress 事件处理程序

    var xhr = createXHR();
    xhr.onload = function(event){
      if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
        alert(xhr.responseText);
      } else {
        alert("Request was unsuccessful: " + xhr.status);
      }
    };
    xhr.onprogress = function(event){
      var divStatus = document.getElementById("status");
      if (event.lengthComputable){
        divStatus.innerHTML = "Received " + event.position + " of " + event.totalSize +" bytes";
      }
    };
    xhr.open("get", "altevents.php", true);
    xhr.send(null);



     

     

  • 相关阅读:
    QTimer::singleShot
    Qt 建立带有子项目的工程
    Qt GlobalColor及其显示
    QT自定义图形项中的boundingRect()和shape()函数的理解
    QT setZValue() 函数
    C++中explicit的作用及用法
    QT中foreach的使用
    QT代码封装成dll和lib文件及使用
    Qt智能指针QScopedPointer
    Qt的四个常见的图像叠加模式
  • 原文地址:https://www.cnblogs.com/shengnan-2017/p/9407503.html
Copyright © 2020-2023  润新知