如何在Ajax中更改JSON数组中的值

时间:2018-06-17 21:13:00

标签: javascript

我在隐藏输入中有一个如下所示的json数组。我试图在按钮点击时使用ajax更新充电值。

[{"2018-06-19":{"charge":55000,"xcharge":15000}},
 {"2018-06-20":{"charge":55000,"xcharge":15000}},
 {"2018-06-21":{"charge":55000,"xcharge":15000}},
 {"2018-06-22":{"charge":55000,"xcharge":15000}},
 {"2018-06-23":{"charge":55000,"xcharge":15000}},
 {"2018-06-24":{"charge":55000,"xcharge":15000}}]

我的隐藏输入和按钮

<input type="hidden" name="chargeArray" id="chargeArray" value='[{"2018-06-19":{"charge":55000,"xcharge":15000}},{"2018-06-20":{"charge":55000,"xcharge":15000}},{"2018-06-21":{"charge":55000,"xcharge":15000}},{"2018-06-22":{"charge":55000,"xcharge":15000}},{"2018-06-23":{"charge":55000,"xcharge":15000}},{"2018-06-24":{"charge":55000,"xcharge":15000}}]' />

<button class="btn btn-default" type="button" onclick="change_room_charge();"><span class="glyphicon glyphicon-edit"></span></button>

我已经尝试过这个,但它失败了。充电值不会改变为新值。

function change_room_charge(){
    var chargeArray = JSON.parse($('#chargeArray').val());

     $.each(chargeArray, function (index, item) {
         item[0].charge = item[0].charge.replace(666);
     });

     $('#chargeArray').val(JSON.stringify(chargeArray));
}

我想要的是将隐藏输入中的所有现有费用值更改为新值。

1 个答案:

答案 0 :(得分:0)

无论你做什么都很奇怪,但我会随之而去。您的对象按日期键入,因此您需要先获取该键。因此,在下面的代码中,我通过查找项目的所有键并获取第一个键来获取密钥。从那里你可以将值设置为你想要的任何值,然后将其放回输入中。

&#13;
&#13;
function change_room_charge() {
  var chargeArray = JSON.parse($('#chargeArray').val());
  $.each(chargeArray, function(index, item) {
    var key = Object.keys(item)[0];
    item[key].charge = 666;
  });
  $('#chargeArray').val(JSON.stringify(chargeArray));
  console.log($('#chargeArray').val());
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="chargeArray" id="chargeArray" value='[{"2018-06-19":{"charge":55000,"xcharge":15000}},{"2018-06-20":{"charge":55000,"xcharge":15000}},{"2018-06-21":{"charge":55000,"xcharge":15000}},{"2018-06-22":{"charge":55000,"xcharge":15000}},{"2018-06-23":{"charge":55000,"xcharge":15000}},{"2018-06-24":{"charge":55000,"xcharge":15000}}]' />
<button class="btn btn-default" type="button" onclick="change_room_charge();">
<span class="glyphicon glyphicon-edit"></span>
</button>
&#13;
&#13;
&#13;