简体   繁体   English

jQuery AJAX JSON数据被展平

[英]jQuery AJAX JSON data is flattened

When I try to send a nested object to my server using $.ajax() , the data received by the backend is flattened. 当我尝试使用$.ajax()将嵌套对象发送到服务器时,后端接收的数据将被展平。 I need to be able to send an object that contains another object to my backend. 我需要能够将包含另一个对象的对象发送到后端。 Here's an example of what's happening: 这是正在发生的事的一个例子:

$.ajax({
  method: 'POST',
  url: '/users/create'
  data: {
    name: 'John Doe',
    age: 42,
    marbles: {
      blue: 4,
      red: 8
    }
  }
})
{
  'name': 'John Doe',
  'age': '42',
  'marbles[blue]': '4',
  'marbles[red]': '8'
}

I am expecting the following: 我期望以下几点:

{
  name: 'John Doe',
  age: 42,
  marbles: {
    blue: 4,
    red: 8
  }
}

Does anyone have a clue what I can do to fix this? 有人知道我能做什么来解决这个问题吗? I have tried adding dataType: 'json' to the AJAX request. 我尝试将dataType: 'json'添加到AJAX请求中。

You need to stringify your object first. 您需要先对对象进行字符串化。

$.ajax({
  method: 'POST',
  url: '/users/create',
  contentType: 'application/json',
  data: JSON.stringify({
    name: 'John Doe',
    age: 42,
    marbles: {
      blue: 4,
      red: 8
    }
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM