我已将以下脚本从基于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);
}