簡體   English   中英

如何從 javascript 變量中制作 php 數組值? [等候接聽]

[英]how to I make php array value from javascript variable? [on hold]

我嘗試使用本地存儲 session 創建購物車,其中我使用 java 腳本收集變量輸入,例如購物車的總價格:

$form.on( "submit", function() {
var qty = self._convertString( $form.find( ".qty" ).val() );
var subTotal = qty * price;
var total = self._convertString( self.storage.getItem( self.total ) );
var sTotal = total + subTotal;
self.storage.setItem( self.total, sTotal );
self._addToCart({
product: name,
price: price,
qty: qty
});

然后我需要使用 php 數組將輸入傳遞給在線支付提供商:

$ParametersArray = array(
"amount" => "2700.00",
"currency" => "USD",
"description" => "Product 01",

如何將 php 數組鏈接到 js 變量,以便數組顯示購物車輸入? 例如:“amount”將打印 sTotal 值

我不是 100% 確定你的問題是什么意思,但這是如何將 PHP 數組轉換為 JS 變量:

<?php
<script>
    const phpToJs = <?= json_encode($php_array) ?>;
</script>

and then depending on our HTTP library, eg axios, jQuery AJAX, fetch, etc. you can usually pass in arrays and set the header Content-Type to application/json.

JS 示例:

注意:我還沒有測試 fetch ,我只是查找了一些文檔以獲取正確的數據以通過,所以希望它可以工作。

const data = {
    product: name,
    price,
    qty,
};

// Axios
axios({ url: '/endpoint', method: 'post', data })
    .then(response => {
        // Deal with the successful response.
    })
    .catch(error => {
        // Deal with the error.
    });

// jQuery AJAX
$.post('/endpoint', data)
    .then(response => {
        // Deal with the successful response.
    })
    .catch(error => {
        // Deal with the error.
    });

// Fetch.
const fetchInfo = {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
};

fetch(fetchInfo)
    .then(response => {
        // Deal with the response.
        if (response.ok) {
            // 
        } else {
            throw new Error();
        }
    })
    .catch(error => {
        // Deal with the error.
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM