使用Ajax向Json响应追加元素

Append element to Json response using Ajax

本文关键字:追加 元素 响应 Json Ajax 使用      更新时间:2023-09-26

我有一些麻烦弄清楚。我有一个Json响应:

[
  {
    "id": 82797,
    "name": "pom-ta-all",
    "date": "2016-06-26T11:57:53+0000",
    "creationDate": "2016-06-10T14:15:00+0000",
    "version": "1.0.0",
  },
  {
    "id": 80926,
    "name": "pom-evnthdl-wln-all",
    "creationDate": "2016-06-03T17:44:20+0000",
    "version": "1.1.0",
  }...

,我得到从rest api使用Jquery Ajax。如何在Ajax调用中向每个元素添加当前日期,使其看起来像这样:

[
      {
        "id": 82797,
        "name": "pom-ta-all",
        "date": "2016-06-26T11:57:53+0000",
        "creationDate": "2016-06-10T14:15:00+0000",
        "version": "1.0.0",
        "currentDate": "2016-06-28"
      },...

我可以使用.append()吗?如果有,怎么做?总的来说,我对Ajax和JavaScript不是很熟悉。格式最好是这样的:

var job = $.ajax({
    url: url,
    dataType: 'json',
    data: data,
    success: #insert magic here, <---
    error: function()
  });

谢谢你的想法

你的成功函数

...
success: function(json) {
    $.each(json, function(idx) {
       json[idx].currentDate = new Date();
    });
}
...

工作示例,基于inputData

var json = [
  {
    "id": 82797,
    "name": "pom-ta-all",
    "date": "2016-06-26T11:57:53+0000",
    "creationDate": "2016-06-10T14:15:00+0000",
    "version": "1.0.0",
  },
  {
    "id": 80926,
    "name": "pom-evnthdl-wln-all",
    "creationDate": "2016-06-03T17:44:20+0000",
    "version": "1.1.0",
  }];
  
  
  
  $.each(json, function(idx) {
     json[idx].currentDate = new Date();
  });
  
  console.log(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

如何使用JS格式化当前日期?请参阅其他人的建议:

如何在JavaScript中获得当前日期?