使用jquery从JSON中删除数组中的所有项

时间:2013-12-07 20:21:48

标签: jquery arrays json

我有一个JSON数据,我想要删除数组中的所有项目,我已经尝试删除,Products.length = 0但没有任何作用。我可以添加新项目,修改和删除特定项目,但无法删除所有项目。

JSON数据

{
   "Products":[
      {
         "productID":"75",
         "productName":"Mango Juice",
         "productQuantity":3,
         "seller_1":"30.00",
         "seller_2":"40.00",
         "seller_3":"34.50"
      },
      {
         "productID":"25",
         "productName":"Apple Juice",
         "productQuantity":1,
         "seller_1":"70.00",
         "seller_2":"74.00",
         "seller_3":"84.50"
      },
      {
         "productID":"10",
         "productName":"Orange Juice",
         "productQuantity":1,
         "seller_1":"10.00",
         "seller_2":"20.00",
         "seller_3":"12.50"
      }
   ]
}

删除所有项目后,我应该将其作为最终

{"Products": []}

这是Jquery过程

$(document).ready(function() {
    $.getJSON( "data.json", function(data) {
           data.Products = [];
            $.ajax({
            type: "POST",
            url: "json.php",
            dataType: 'json',
            data: { json: data }
        });
    });
});

Php过程

if(isset($_POST['json'])) {
    $fp = fopen('data.json', 'w+');
    fwrite($fp, json_encode($_POST['json']));
    fclose($fp);
}

的console.log(数据);显示代码已在javascript端执行得很好,但它不会通过PHP更新JSON

2 个答案:

答案 0 :(得分:2)

如果你有这个:

var data = {
   "Products":[
      {
         "productID":"75",
         "productName":"Mango Juice",
         "productQuantity":3,
         "seller_1":"30.00",
         "seller_2":"40.00",
         "seller_3":"34.50"
      },
      {
         "productID":"25",
         "productName":"Apple Juice",
         "productQuantity":1,
         "seller_1":"70.00",
         "seller_2":"74.00",
         "seller_3":"84.50"
      },
      {
         "productID":"10",
         "productName":"Orange Juice",
         "productQuantity":1,
         "seller_1":"10.00",
         "seller_2":"20.00",
         "seller_3":"12.50"
      }
   ]
}

然后,您可以这样做:

data.Products = [];

这只会将data.Products设置为新创建的空数组。

如果你有任何理由想要保持相同的数组(例如你想要指向空数组的引用),你也可以这样做:

data.Products.length = 0;

注意:还有很多其他方法可以做到这一点,包括拼接所有元素,弹出所有元素等等...通过删除项而不是分配新的空数组修改原始数组将修改数组任何外部引用也可能指向(根据具体情况你可能想要或不想要)。


仅供参考,JSON是一种文本格式。你在这里有一个javascript对象。两者不一样。

答案 1 :(得分:0)

您可以尝试使用拼接功能

var arr =[1,2,3,4];
arr.splice(0,arr.length);