скрипт не работает после конвертации из jquery в javascript - PullRequest
2 голосов
/ 21 февраля 2020

Я преобразовал следующий скрипт из jquery на основе ajax в Pure 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>

1 Ответ

1 голос
/ 21 февраля 2020

Чтобы отправить закодированное сообщение формы в 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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...