通过AJAX发送数据WITHIN JSON

时间:2017-11-14 07:39:44

标签: javascript jquery json ajax

我想在数组地址中附加另一个 home_address

  "fieldlist": [
    {
      "id": 1,
      "street_name": "N. 10th",
      "address": [
        {
          "aid": 1,
          "home_address": "5801",
          "city": "Philadelphia"
        },
        {
          "aid": 2,
          "home_address": "5802",
          "city": "Philadelphia"
        }
      ]
    }
  ]
}

问题是代码被添加到最后。

"fieldlist": [
    {
      "id": 1,
      "street_name": "N. 10th",
      "address": [
        {
          "aid": 1,
          "home_address": "5801",
          "city": "Philadelphia"
        },
        {
          "aid": 2,
          "home_address": "5802",
          "city": "Philadelphia"
        }
      ]
    },
    {
      "aid": 4,
      "home_address": "5804",
      "id": 2
    }
  ]
}

这是我的样本ajax代码

var addnumber = {
                  "aid": 4,
                  "home_address": "5804"
            }

     $.ajax({
                    type:'POST',
                    url: 'http://localhost:3000/fieldlist',
                    data: JSON.stringify(addnumber),
                    contentType: 'application/json',
                    dataType: 'json'

        });

无论如何,我可以在地址 array中附加,而不是在代码块之后?或者我应该更改JSON的结构?

2 个答案:

答案 0 :(得分:1)

访问fieldlist[0].address并推入fieldlist而不是var fieldlist = [ { "id": 1, "street_name": "N. 10th", "address": [ { "aid": 1, "home_address": "5801", "city": "Philadelphia" }, { "aid": 2, "home_address": "5802", "city": "Philadelphia" } ] } ]; const newAddr = {"aid": 4, "home_address": "5804", "id": 2 }; fieldlist[0].address.push(newAddr); console.log(fieldlist);

Manager:
Manager_employee_id(PK)
Manager_Bonus

Project:
project_number(PK)
Project_cost
Project_manager_employee_id(FK)

答案 1 :(得分:0)

谢谢你们,我想我已经明白了。抱歉,我是ajax的新手。首先......我必须使用PUT请求。我以为只有帖子。 2,我必须使用正确的路径到json url。我失去了,直到我发布这个,所以感谢快速的回应。