zoukankan      html  css  js  c++  java
  • 常用的一段ajax的代码

    下面的代码是我经常使用的一段代码,发上来以备忘
    /*-----------------------------
    ajax关键代码
    将ajax封装成一个类
    -----------------------------*/
    function createAjax() {
        var xmlHttp = false;
        if (window.XMLHttpRequest) {
            //mozilla
            xmlHttp = new XMLHttpRequest();//ie6不支持XMLHttpRequest
            if (xmlHttp.overrideMimeType) xmlHttp.overrideMimeType("text/xml");
     
     
        }
        else if (window.ActiveXObject) {                
            var MSXML = ['MSXML2.XMLHTTP.5.0', 'Microsoft.XMLHTTP', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
            var i;
            for(i = 0; i < MSXML.length; i++){
                try{
                    xmlHttp = new ActiveXObject(MSXML[i]);
                    break;
                }
                catch(e){}
            }    
        }
        if (!xmlHttp) { alert("error! fail to create an ajax instance!"); return false; }
     
        this.rep = xmlHttp;
     
        this.sendData = function(method, url, asy, fun) {
            if (asy) {
                xmlHttp.onreadystatechange = function() {
                    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                        fun(xmlHttp);
                    }
                }
                if (method == "POST") {
                    xmlHttp.open("POST", url, true);
                    xmlHttp.setRequestHeader("Conent-Type", "application/x-www-form-urlencoded");
                    xmlHttp.send(null);
                }
                else {
                    xmlHttp.open("GET", url, true);
                    xmlHttp.send(null);
                }
            }
            else {
                if (method == "POST") {
                    xmlHttp.open("POST", url, false);
                    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xmlHttp.send(null);
                }
                else {
                    xmlHttp.open("GET", url, false);
                    xmlHttp.send(null);
                }
                return xmlHttp;
            }
        }
    }

    使用:

    先实例一个对象:

       1: var ajax = new createAjax();
     
     
    再写方法:
       1: ajax.sendData("POST", "articleEdit.aspx?RemoveAttachmentID=" + attachmentID + "&NewsID=" + newsID, true, function(xmlhttp) {
       2:     if (xmlhttp.responseText != "") {
       3:         
       4:     //to do something
       5:  
       6:     }
       7: })
  • 相关阅读:
    详解Webpack-dev-server的proxy用法
    .sync修饰符
    [Vue]createElement参数
    ElementUi学习笔记
    A5000项目阅读笔记
    webpack学习-10天搞定webpack4
    bhuilder 采坑日记-大小写问题
    angularjs:$$animateJs is not a function 错误
    webpack4 Cannot find module '@babel/core'
    算法-图论-最短路径-Dijsktra算法
  • 原文地址:https://www.cnblogs.com/poissonnotes/p/1681642.html
Copyright © 2011-2022 走看看