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: })
  • 相关阅读:
    iOS 发布流程
    iOS 生产证书
    iOS自定义字体及类目
    iOS动画特效
    iOS调用相机,相册,上传头像
    iOS中UITextField 使用全面解析
    iOS开发UITableView基本使用方法总结
    iOS开发网络数据之AFNetworking使用
    苹果App Store开发者帐户从申请,验证,到发布应用(4)
    苹果App Store开发者帐户从申请,验证,到发布应用(3)
  • 原文地址:https://www.cnblogs.com/poissonnotes/p/1681642.html
Copyright © 2011-2022 走看看