zoukankan      html  css  js  c++  java
  • 异步对象(XMLHttpRequest)的帮助脚本

    异步对象五部曲

    这是post请求的、

     //1.00创建异步对象
                var xhr = new XMLHttpRequest();
                //2.0
                xhr.open("post", url,params, true);
                //3.0将参数使用Formdata属性传递
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    
                //4.0设置回调函数
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        alert(xhr.responseText);
    
                    }
                }
    
                //5.0传递参数
                xhr.send(params);

    结合get请求做一个异步对象的封装

    get 请求中的

      xhr.setRequestHeader("If-Modified-Since", "0"); 是为了清除缓存

    而post请求的
     xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    是为了传输方式
    在<from method='post' type="">
    <from>中的type可以得到三种方式,其中包括application/x-www-form-urlencoded
    var ajaxHelp = {
        CreatXHR: function () {
            //创建异步对象
            var xhr = new XMLHttpRequest();
            return xhr;
        },
        //ajax的get请求
        AjaxGet: function (url, callBack) {
            this.AJaxCommon("get", url, null, callBack);
        },
        //ajax的post请求
        AjaxPost: function (url, params, callBack) {
            this.AJaxCommon("post", url, params, callBack);
        },
        AJaxCommon: function (method, url, params, callBack) {
            //1.0
            var xhr = this.CreatXHR();
            //2.0
            xhr.open(method, url, true);
            //3.0
            if (method == "get") {
                xhr.setRequestHeader("If-Modified-Since", "0");
            } else {
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
            //4.0
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var datas = JSON.parse(xhr.responseText);
                    //执行回调函数
                    callBack(datas);
                }
            }
            //5.0
            xhr.send(params);
        }
    };

    ps:在JQuery里面是有$.ajax  和$.get /   $.Post  等异步请求的方法的。以前的封装就不用了。额。好扯。其实他们底层也是这样的写的呢。JQuery就是为了解决各个浏览器的兼容性问题而已

  • 相关阅读:
    django集成django-xadmin
    Django设置 DEBUG=False后静态文件无法加载解决
    Django ORM必会的查询方法
    django admin-过滤器
    Django settings.py 中设置访问 MySQL 数据库【一种是直接在 settings.py 文件中直接写数据库信息,另一种是读文件获取数据库信息】
    django-admin之ModelAdmin最全解释
    SPL(Standard PHP Library 标准PHP类库)
    rsync 数据同步
    PHP 安装memcache.so 和memcached.so
    linux 安装memcached
  • 原文地址:https://www.cnblogs.com/aguan/p/4102744.html
Copyright © 2011-2022 走看看