我已将以下脚本从基于 jquery 的 Ajax 转换为纯基于 javascript 的 Ajax,但它不起作用
这是基于 Jquery 的脚本
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'
});
}
}
这里是转换后的Javascript代码
function addCart(elements, product_id, quantity) {
// Creating the XMLHttpRequest object
var request = new XMLHttpRequest();
// Instantiating the request object
request.open("POST", "/index.php?route=checkout/cart/add", true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
// Defining event listener for readystatechange event
request.onreadystatechange = function() {
// Check if the request is compete and was successful
if(this.readyState === 4 && this.status === 200) {
alert("Success");
}
};
var data = 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1);
// Sending the request to the server
request.send(data);
}
我认为发送数据可能存在问题,因为我对此不太了解。
我将 HTML 更改为
<button type="button" onclick="cart.add('{{product_id }}', '{{minimum }}');">Add</button>
到
<button type="button" onclick="addCart(this, '{{product_id }}', '{{minimum }}');">Add</button>
最佳答案
为了在 JS 中发送表单编码消息,您需要提交表单或创建一个 FormData
对象。对于您的情况,我们将创建一个 FormData
。
// Set the needed params.
let formData = new FormData();
const finalQuantity = typeof(quantity) != 'undefined' ? quantity : 1;
formData.append('product_id', product_id);
formData.append('quantity', finalQuantity);
现在,我建议使用新的 fetch API
而不是使用 XMLHttpRequest
。因此,您的请求将类似于以下代码。
fetch('index.php?route=checkout/cart/add', {
method: 'POST',
body: formData,
}))
.then(response => response.json())
.then(() => {
console.log('Success.');
}).catch(error => {
console.log(error.message);
}).finally(function () {
console.log('Something you wanna execute even if you caught an error or if the request was successful.');
});
在我看来,由于类似的结构,它更容易理解,并且更容易从 jQuery 翻译。
因此,进行所有相应的更改后,您的方法最终将如下所示。
function addCart(element, product_id, quantity) {
// Set the needed params.
let formData = new FormData();
const finalQuantity = typeof(quantity) != 'undefined' ? quantity : 1;
formData.append('product_id', product_id);
formData.append('quantity', finalQuantity);
fetch('index.php?route=checkout/cart/add', {
method: 'POST',
body: formData,
}))
.then(response => response.json())
.then(() => {
console.log('Success.');
}).catch(error => {
console.log(error.message);
}).finally(function () {
console.log('Something you wanna execute even if you caught an error or if the request was successful.');
});
}
如果不允许fetch
,由于浏览器兼容性的原因,我们仍然可以使用XMLHttpRequest
。您的代码只需要一些小的更改。
function addCart(elements, product_id, quantity) {
// Build the form data.
let formData = new FormData();
const finalQuantity = typeof(quantity) != 'undefined' ? quantity : 1;
formData.append('product_id', product_id);
formData.append('quantity', finalQuantity);
// Creating the XMLHttpRequest object
const request = new XMLHttpRequest();
// Instantiating the request object
request.open("POST", "/index.php?route=checkout/cart/add");
// Defining event listener for readystatechange event
request.onreadystatechange = function() {
// Check if the request is compete and was successful
if(this.readyState === 4 && this.status === 200) {
alert("Success");
}
};
request.send(formData);
}
关于javascript - 脚本从 jquery 转换为 javascript 后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60340113/