javascript - 使用 Ajax 将元素附加到 Json 响应

标签 javascript json

我在解决这个问题时遇到了一些麻烦。我有一个 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",
  }...

我使用 Jquery Ajax 从 REST API 获取。如何在 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();
    });
}
...

基于您的输入数据的工作示例

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 格式化的当前日期,请参阅其他人的建议:

How do I get the current date in JavaScript?

关于javascript - 使用 Ajax 将元素附加到 Json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38079441/

相关文章:

javascript - 使用 Angular 服务在 Controller 之间共享数据

javascript - 在 javascript toString() 中添加不同的分隔符..?

javascript - 如何获取 maxGraph 单元格内容的 ID

javascript - window.scroll() 函数未触发

javascript - 在 webkit 浏览器检查器时间轴中显示自定义事件

json - Ansible 合并 2 个数组

java - 使用 Java 检查一个值是否存在于 JSON 对象中

javascript - 如何使用 angularjs ng-repeat 从 json 获取特定值并在 html 中显示

javascript - datatables.js 不重新加载仅显示

php - JSON 输入意外结束 - Uncaught SyntaxError