简体   繁体   English

从 JSON 响应中获取购物车 ID

[英]Get Cart Id from JSON response

I need to capture the cartID in a js variable from a JSON response.我需要从 JSON 响应中捕获 js 变量中的 cartID。

So far I have the following code which requests the cart information.到目前为止,我有以下代码请求购物车信息。

 function getCart(url) { return fetch(url, { method: "GET", credentials: "same-origin" }).then(response => response.json()) }; var cartID = 'unknown'; getCart('/api/storefront/carts').then(data => console.log(JSON.stringify(data))).catch(error => console.error(error));

The console.log data is formatted like this: console.log 数据的格式如下:

 Extract of full data: [{"id":"c5f24d63-cd9a-46f2-be41-6ad31fc38b51","customerId":1,"email":"me@gmail.com", ................. }]

I have tried various methods to capture the cart ID to variable cartID, but each time it shows 'unknown' and is logged before the data response.我尝试了各种方法将购物车 ID 捕获到变量 cartID,但每次它显示“未知”并在数据响应之前记录。

Any ideas how to delay until the response is ready and then 'cartID' with the id value?任何想法如何延迟直到响应准备好然后'cartID'和id值?

Because the response if a JSON array, you can try to loop and extract the cartID from each cart object:因为如果响应为 JSON 数组,您可以尝试循环并从每个购物车 object 中提取购物车 ID:

function getCart(url) {
    return fetch(url, {
        method: "GET",
        credentials: "same-origin"
    })
    .then(response => response.json())
 };
 
 var cartID = 'unknown';
 
 getCart('/api/storefront/carts')
 .then(
     data => {
         //The response is an array of cart objects. We need to extract the ID from the array
         cartID = data[0].id;

         //Or loop through the response and extract the ID from each cart object
         for (var i = 0; i < data.length; i++) {
             cartID = data[i].id;
         }
     }
     )
 .catch(error => console.error(error));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM