如何将jquery ajax转换为本机javascript? [英] How to convert jquery ajax to native javascript?

查看:40
本文介绍了如何将jquery ajax转换为本机javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的ajaxHandler,我想将其转换为本地javascript,即 使用XMLHttpRequest,但是我不明白如何转换.

 ajaxHandler = {
  defaultAttributes: {
    type: 'GET',
    url: 'index.php/request',
    datatype: 'json',
    data: {},
    success: null,
    error: function(data) {
      errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
    },
    timeout: function() {
      errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
    }
  },
  sendRequest: function(attributes) {
    Paper.giffyLoading.style.display = 'block';
    if (!attributes.nopopup) {
      if (attributes.loadmsg) {
        Controllers.AnimationController.createProgressBarScreen(attributes.loadmsg);
        attributes.loadmsg = null;
      }
    }
    $.ajax(attributes);
  }
} 

我尝试像这样转换上面的代码

 XMLRequestDefaultHandler = function() {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open('GET', 'index.php/request', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState === 4 || xmlHttp.status === 200) {

    } else {
      errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');


    }
  };
  xmlHttp.send(null);

} 

解决方案

我提取了Jquery的ajax函数,以在不使用jquery的情况下工作.

并将$.ajax(attributes);替换为ajax(attributes);

没有JQuery的JQuery的ajax函数:

function ajax(option) { // $.ajax(...) without jquery.
    if (typeof(option.url) == "undefined") {
        try {
            option.url = location.href;
        } catch(e) {
            var ajaxLocation;
            ajaxLocation = document.createElement("a");
            ajaxLocation.href = "";
            option.url = ajaxLocation.href;
        }
    }
    if (typeof(option.type) == "undefined") {
        option.type = "GET";
    }
    if (typeof(option.data) == "undefined") {
        option.data = null;
    } else {
        var data = "";
        for (var x in option.data) {
            if (data != "") {
                data += "&";
            }
            data += encodeURIComponent(x)+"="+encodeURIComponent(option.data[x]);
        };
        option.data = data;
    }
    if (typeof(option.statusCode) == "undefined") { // 4
        option.statusCode = {};
    }
    if (typeof(option.beforeSend) == "undefined") { // 1
        option.beforeSend = function () {};
    }
    if (typeof(option.success) == "undefined") { // 4 et sans erreur
        option.success = function () {};
    }
    if (typeof(option.error) == "undefined") { // 4 et avec erreur
        option.error = function () {};
    }
    if (typeof(option.complete) == "undefined") { // 4
        option.complete = function () {};
    }
    typeof(option.statusCode["404"]);

    var xhr = null;

    if (window.XMLHttpRequest || window.ActiveXObject) {
        if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } }
        else { xhr = new XMLHttpRequest(); }
    } else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return null; }

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 1) {
            option.beforeSend();
        }
        if (xhr.readyState == 4) {
            option.complete(xhr, xhr.status);
            if (xhr.status == 200 || xhr.status == 0) {
                option.success(xhr.responseText);
            } else {
                option.error(xhr.status);
                if (typeof(option.statusCode[xhr.status]) != "undefined") {
                    option.statusCode[xhr.status]();
                }
            }
        }
    };

    if (option.type == "POST") {
        xhr.open(option.type, option.url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        xhr.send(option.data);
    } else {
        xhr.open(option.type, option.url+option.data, true);
        xhr.send(null);
    }

}

here is my ajaxHandler i want to convert this to native javascript i.e using XMLHttpRequest but i am unable to understand how to convert.`

ajaxHandler = {
  defaultAttributes: {
    type: 'GET',
    url: 'index.php/request',
    datatype: 'json',
    data: {},
    success: null,
    error: function(data) {
      errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
    },
    timeout: function() {
      errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
    }
  },
  sendRequest: function(attributes) {
    Paper.giffyLoading.style.display = 'block';
    if (!attributes.nopopup) {
      if (attributes.loadmsg) {
        Controllers.AnimationController.createProgressBarScreen(attributes.loadmsg);
        attributes.loadmsg = null;
      }
    }
    $.ajax(attributes);
  }
}

i have try to convert the above code like this

XMLRequestDefaultHandler = function() {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open('GET', 'index.php/request', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState === 4 || xmlHttp.status === 200) {

    } else {
      errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');


    }
  };
  xmlHttp.send(null);

}

解决方案

I extracted ajax function of Jquery, to work without jquery.

And replace $.ajax(attributes); to ajax(attributes);

JQuery's ajax function, without JQuery :

function ajax(option) { // $.ajax(...) without jquery.
    if (typeof(option.url) == "undefined") {
        try {
            option.url = location.href;
        } catch(e) {
            var ajaxLocation;
            ajaxLocation = document.createElement("a");
            ajaxLocation.href = "";
            option.url = ajaxLocation.href;
        }
    }
    if (typeof(option.type) == "undefined") {
        option.type = "GET";
    }
    if (typeof(option.data) == "undefined") {
        option.data = null;
    } else {
        var data = "";
        for (var x in option.data) {
            if (data != "") {
                data += "&";
            }
            data += encodeURIComponent(x)+"="+encodeURIComponent(option.data[x]);
        };
        option.data = data;
    }
    if (typeof(option.statusCode) == "undefined") { // 4
        option.statusCode = {};
    }
    if (typeof(option.beforeSend) == "undefined") { // 1
        option.beforeSend = function () {};
    }
    if (typeof(option.success) == "undefined") { // 4 et sans erreur
        option.success = function () {};
    }
    if (typeof(option.error) == "undefined") { // 4 et avec erreur
        option.error = function () {};
    }
    if (typeof(option.complete) == "undefined") { // 4
        option.complete = function () {};
    }
    typeof(option.statusCode["404"]);

    var xhr = null;

    if (window.XMLHttpRequest || window.ActiveXObject) {
        if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } }
        else { xhr = new XMLHttpRequest(); }
    } else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return null; }

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 1) {
            option.beforeSend();
        }
        if (xhr.readyState == 4) {
            option.complete(xhr, xhr.status);
            if (xhr.status == 200 || xhr.status == 0) {
                option.success(xhr.responseText);
            } else {
                option.error(xhr.status);
                if (typeof(option.statusCode[xhr.status]) != "undefined") {
                    option.statusCode[xhr.status]();
                }
            }
        }
    };

    if (option.type == "POST") {
        xhr.open(option.type, option.url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        xhr.send(option.data);
    } else {
        xhr.open(option.type, option.url+option.data, true);
        xhr.send(null);
    }

}

这篇关于如何将jquery ajax转换为本机javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆