javascript - 将 Native Promise 转换为 JQuery 的 Promise(适用于 IE)

标签 javascript jquery promise

我目前严重依赖 Javascript 中的 native “Promise”对象来执行 AJAX 调用。但是,正如 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise 中提到的经过我在 IE11 中的测试, native promise 在 IE 中不起作用。

现在,解决方案是使用 JQuery 的 Promises,但我无法使其工作。 请找到以下 Native Promise 代码:(适用于除 IE 之外的所有浏览器)

var getJSON = function (url) {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        console.log(window.location);
        console.log(window.location.origin);
        xhr.open('get', url, true);
        xhr.withCredentials = true;
        xhr.responseType = 'application/json';
        xhr.onload = function () {
            var status = xhr.status;
            if (status == 200) {
                resolve(xhr.response);
            } else {
                reject(status);
            }
        };
        xhr.send();
    });
};

getJSON(url).then(function (data) {
    console.log(data);
    console.log("Success");           
}, function (status) { //error detection....
    console.log(status);
    alert('Something went wrong.');
});*/

我尝试过类似的方法,但没有成功

 var promise = $.ajax({
    url: url,
    beforeSend: function (xhr) {
        xhr.withCredentials = true;
    }
}).done(function (data){
    console.log(data);  
});

我认为我们必须使用延迟对象,但无法弄清楚! 注意:由于缺少 Node.js,无法使用 PolyFill 或 BlueBird 谢谢

最佳答案

var p = $.ajax({
    url: "yoururl",
    type: "GET",
    dataType: 'json',
    xhrFields: {
         withCredentials: true
    }
});
// use p.then()

注意:
jQuery 直接有一个 $.JSON() 函数。
另外,看看Promise-Polyfill如果你只是想要 promise !

关于javascript - 将 Native Promise 转换为 JQuery 的 Promise(适用于 IE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38619558/

相关文章:

javascript - 如何在 DOM 中创建没有 SVG 元素的 SVG 矩阵

javascript - ES6 迭代器的用例

javascript - Angular $q.reject().success(),这有意义吗?

javascript - DOM appendChild 没有给出正确的输出

C# Web服务,如何接收JSON

JQuery如何选择表格单元格并设置边框并取消选择上一个单元格

ajax - 跨域ajax - 对我有用

javascript - 是否可以使用 HTML 从任意字符串创建 Jquery 对象,例如变种 $newlink = $ ('<a>new link</a>' )

javascript - promise/defer 库是如何实现的?

node.js - 在 Node/Express 中,如何使用 csv-to-array 来匹配或比较嵌套 Promise 中的值