首页 > 解决方案 > 如何将基于 Jquery 和 Ajax 的脚本转换为纯 Javascript

问题描述

我想将以下基于 jquery 和 ajax 的脚本转换为纯 javascript

var cart = {
    'add': function(product_id, quantity) {
        $.ajax({
            url: 'index.php?route=checkout/cart/add',
            type: 'post',
            data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
            dataType: 'json',
            beforeSend: function() {
                $('#cart > button').button('loading');
            },
            complete: function() {
                $('#cart > button').button('reset');
            },
            success: function(json) {

                if (json['redirect']) {
                    location = json['redirect'];
                }

                    $('#cart > ul').load('index.php?route=common/cart/info ul li');
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    }
}

我试过了,但我认为我做错了一切

我关注了https://github.com/nefe/You-Dont-Need-jQueryhttp://youmightnotneedjquery.com/作为我的参考资料

任何人都可以帮助我解决这个问题

 var cart = {
    'add': function(product_id, quantity) {
        var request = new XMLHttpRequest();
        request.open('POST', 'index.php?route=checkout/cart/add', true);

        request.onload = function() {
            if (this.status >= 200 && this.status < 400) {

                if (json['redirect']) {
                    location = json['redirect'];
                }

                fetch('index.php?route=common/cart/info ul li').then(data => data.text()).then(data => {
                    document.querySelector('#cart > ul').innerHTML = data
                }).then(completeCallback)



                var json = this.response;
            }
        };

        request.onerror = function(xhr, ajaxOptions, thrownError) {
            alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        };

        request.send('product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1));
    }
}

标签: javascriptjqueryajax

解决方案


推荐阅读