javascript - 如何将基于 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-jQuery和http://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));
}
}
解决方案
推荐阅读
- php - Symfony/PostGreSQL:驱动程序发生异常:找不到驱动程序
- r - 如何转换我的数据框以制作行列?
- asp.net-core - IIS 502.3 崩溃但仅来自 Electron
- node.js - 在后台任务完成之前返回的 Lambda 函数
- c# - NET CORE Json 模型绑定保存 EF
- python - Pandas 是否发布 GIL 用于字符串比较?
- java - 错误链表 peek() 不为空且 size() =0
- python-3.x - Pyinstaller 在可执行文件中不包括 pywin32-ctypes
- javascript - 滚动时如何移动图像?
- r - 在 R 中重新格式化 JSON 文件