Javascript 从HTML和PrePre数组中获取json以通过js发送
我有一张桌子Javascript 从HTML和PrePre数组中获取json以通过js发送,javascript,php,html,json,Javascript,Php,Html,Json,我有一张桌子 <table class="cart-table core_storeCartProducts" data-minimal-order-price="0" data-products="{1912c6c3:{amount:1,id:1916,options:{}},17014bb1:{amount:1,id:3231,options:{}},0b2a5c4b:{amount:1,id:4122,options:{}}}"> 我需要从数据产品中获取id,然后发送到car
<table class="cart-table core_storeCartProducts" data-minimal-order-price="0" data-products="{1912c6c3:{amount:1,id:1916,options:{}},17014bb1:{amount:1,id:3231,options:{}},0b2a5c4b:{amount:1,id:4122,options:{}}}">
我需要从数据产品中获取id,然后发送到cart.php。
有人知道吗?使用JQuery+JSON解析函数
var data = $("table").attr("data-products"); // get string
data = JSON.parse(data); // convert to JSON
var id = data.1912c6c3.id; // get id
现在通过AJAX将其发送到您的cart.php
$.ajax({
url: 'cart.php',
data: {idToSend: id},
success:function(response){
//handle the response
},
error: function(err){
// handle the error code
}
});
获取元素属性并解析数据
var idList = [];
var productArray = JSON.parse(document.getElementsByClassName("core_storeCartProducts")[0].getAttribute('data-products')); //get attribute and parse data
for (const i in productArray) {
idList.push(productArray[i]['id']); //collect all product id
}
console.log(idList);
// pass idList to php using ajax
请编辑您的问题并使其更具可读性…P.S您想发送哪个ID?他们所有人?OP没有提到他们有jQuery可用。他们可能不想使用它。如果一般没有提到,你应该提供一个简单的JS解决方案。今天,每个@ADysonIt的用户都可以下载JQuery,但这并不意味着每个人都在使用它,或者想要使用它,或者被允许在他们的项目中使用它。最好是给某人一个他们绝对可以使用的解决方案。如果问题被标记为jQuery,那么jQuery解决方案就可以了,如果不是,那么就不要了。如果没有提到,你不会随机给他们一个基于AngularJS的解决方案,对吗?同意。。。但是JQuery在一般项目中几乎是允许的,我们不知道这是什么类型的项目,以及有什么约束。或者它可能只是OP可能已经在原始JS中编写了其他所有内容,或者使用了其他库,而不想使用jQuery处理这样的随机位。最好留下评论,询问他们是否接受jQuery的答案。哦,如果你有2分钟的时间,把它重新写成原始JS并不难。而且我猜它应该发送所有的ID,而不仅仅是一个