如何从json-server存储db.json中的对象数组

时间:2017-04-02 11:12:24

标签: javascript jquery json json-server

我正在使用json-server创建一个假后端,以json格式存储一些数据。数据很复杂如下 -

   {
        "id": 0,
        "quizName": "Which Harry Potter Character Are You?",
        "characters": ["Harry", "Ron", "Hermoine"],
        "qa": [{
                "question": "Do you play Chess?",
                "answers": [{
                        "name": "yes",
                        "charscore": [0, 1, 0]
                    },
                    {
                        "name": "no",
                        "charscore": [1, 0, 1]
                    }
                ]
            },
            {
                "question": "Do you spell magic correctly?",
                "answers": [{
                        "name": "yes",
                        "charscore": [0, 0, 1]
                    },
                    {
                        "name": "no",
                        "charscore": [1, 1, 0]
                    }
                ]
            },
            {
                "question": "Do you have a Scar?",
                "answers": [{
                        "name": "yes",
                        "charscore": [1, 0, 0]
                    },
                    {
                        "name": "no",
                        "charscore": [0, 1, 1]
                    }
                ]
            }
        ]
    }

但是当我对json-server执行jQuery POST时,json数据存储如下 -

{
  "quizName": "Which Harry Potter Character Are You?",
  "characters[]": [
    "Harry",
    "Ron",
    "Hermoine"
  ],
  "qa[0][question]": "Do you play Chess?",
  "qa[0][answers][0][name]": "yes",
  "qa[0][answers][0][charscore][]": [
    "0",
    "1",
    "0"
  ],
  "qa[0][answers][1][name]": "no",
  "qa[0][answers][1][charscore][]": [
    "1",
    "0",
    "1"
  ],
  "qa[1][question]": "Do you spell magic correctly?",
  "qa[1][answers][0][name]": "yes",
  "qa[1][answers][0][charscore][]": [
    "0",
    "0",
    "1"
  ],
  "qa[1][answers][1][name]": "no",
  "qa[1][answers][1][charscore][]": [
    "1",
    "1",
    "0"
  ],
  "qa[2][question]": "Do you have a Scar?",
  "qa[2][answers][0][name]": "yes",
  "qa[2][answers][0][charscore][]": [
    "1",
    "0",
    "0"
  ],
  "qa[2][answers][1][name]": "no",
  "qa[2][answers][1][charscore][]": [
    "0",
    "1",
    "1"
  ],
  "id": 1
}

post方法如下 -

$.post(this.serverUrl, val, function (serverResponse) {
      //val contains the expected javascript object
      console.log(serverResponse);
});

如何在json-server中正确存储值?

1 个答案:

答案 0 :(得分:1)

修改AJAX调用以发送stringify对象并设置contentType: "application/json"做了诀窍

修改了AJAX调用,如下所示 -

$.ajax({
      type: "POST",
      url: this.serverUrl,
      data: JSON.stringify(val),
      contentType: "application/json"
 });