javascript - Why is it necessary to call JSON.stringify when submitting object data to server? - Stack Overflow

I am working through a new project using Knockout.js and the ASP.NET web ApiController.Many of the ex

I am working through a new project using Knockout.js and the ASP.NET web ApiController. Many of the examples I see perform some manual JSON serialization before posting the data to the server. Additionally, the request content type is equally often set to "application/json".

I am wondering why this is necessary. I'm assuming there's something I haven't yet encountered that makes this either required or at least preferable.

Currently, I am having no issues sending any data I desire to the server using these jQuery ajax options:

        cache: false,
        traditional: true,
        type: 'POST',

Here's sample JS object and corresponding server-side C# model object that POSTs and binds to the ApiController action method just fine.

//JS object
var requestDataObject = {
    accountId: vm.accountId,
    range: [1, "a'b\"c", 3],
    start: new Date(2012, 12, 12)
};

//C# model object
public class RequestData
{
    public int AccountId { get; set; }
    public string[] Range { get; set; }
    public DateTime Start { get; set; }
}

//Action method signature
[HttpPost]
public HttpResponseMessage GetAccountUsage(RequestData requestData){
    ...

What am I missing?

I am working through a new project using Knockout.js and the ASP.NET web ApiController. Many of the examples I see perform some manual JSON serialization before posting the data to the server. Additionally, the request content type is equally often set to "application/json".

I am wondering why this is necessary. I'm assuming there's something I haven't yet encountered that makes this either required or at least preferable.

Currently, I am having no issues sending any data I desire to the server using these jQuery ajax options:

        cache: false,
        traditional: true,
        type: 'POST',

Here's sample JS object and corresponding server-side C# model object that POSTs and binds to the ApiController action method just fine.

//JS object
var requestDataObject = {
    accountId: vm.accountId,
    range: [1, "a'b\"c", 3],
    start: new Date(2012, 12, 12)
};

//C# model object
public class RequestData
{
    public int AccountId { get; set; }
    public string[] Range { get; set; }
    public DateTime Start { get; set; }
}

//Action method signature
[HttpPost]
public HttpResponseMessage GetAccountUsage(RequestData requestData){
    ...

What am I missing?

Share Improve this question asked Dec 20, 2012 at 22:02 Joseph GabrielJoseph Gabriel 8,5303 gold badges42 silver badges53 bronze badges 5
  • 3 I suppose it's because using traditional POST can only send simple name-value pairs -- everything looks like a string on arrival at the server. Using JSON lets you send more plicated objects. – Blazemonger Commented Dec 20, 2012 at 22:06
  • Where's the JSON.stringify? – Alexander Commented Dec 20, 2012 at 22:08
  • @Blazemonger, Yes, of course - that makes sense. So, the nested object would be passed to server as something like JavaScript's version of ToString() (e.g. [object Object]). Please post as answer when you have a minute. – Joseph Gabriel Commented Dec 20, 2012 at 22:11
  • @JanDvorak, I'm afraid you didn't understand what I meant – Alexander Commented Dec 20, 2012 at 22:16
  • @Alexander, I wasn't calling JSON.stringify at all. It wasn't necessary for what I was doing. I posted this question trying to figure out exactly why it was so popular. I entirely overlooked the point of using JSON vs. simple form values - something about forest and trees es to mind :) – Joseph Gabriel Commented Dec 20, 2012 at 22:19
Add a ment  | 

1 Answer 1

Reset to default 6

Historically, GET (and subsequently POST) can only send key-value pairs, and the keys should be unique.

When PHP came, it defined "if a key contains square brackets, let's build an array". This enabled the programmers to call their checkboxes name="chkbox[]", let the form submit normally, and read $_POST['chkbox'] as an array. Some other server languages defined, "if a key is repeated in the query string, let's build an array".

If the key names[]=1 was to be supported, why not names[a][b][c]=1? The servers knew what they should do: Assign names = {a:{b:{c:"1"}}}.

This enables the programmers to encode objects to query the string, with a few catches:

  • Every value is a string
  • There is no distinction between arrays and objects with numeric keys. PHP doesn't care, but some servers might.
  • There is no way to encode empty objects or arrays. With traditional forms, this results in empty arrays missing. PHP does care. JQuery solves that by sending an empty string instead.
  • It's extremely inefficient as the path has to be repeated for each value: checkboxes[]=ch1&checkboxes[]=ch2&... vs. checkboxes=["ch1","ch2",...]
  • you have to know the target platform as PHP doesn't like traditional (or resort to reading from postVars.get("names[]") on servers that do)
  • some servers don't understand this encoding at all.

With JSON,

  • you can encode numbers, strings, null, ...
  • ... arrays, objects...
  • empty arrays and objects are easy to represent. You don't have to test the presence of each array and object just because it might be empty.
  • no key is ever repeated, so you don't need to keep your keys short
  • there is no confusion how to represent an array with automatic keys; a JSON encodes the same structure no matter where it's sent.
  • Parsing JSON is possible in any language. Lot of languages have JSON support built in, the rest can fetch a library.
  • you only have to write one extra line on the server and the client.

In short, if you only need to encode key-value pairs, that's what a plain GET or POST excels at. If you need to encode arrays, JSON is definitely worth considering. If you need anything more plex, JSON is the only way to go with some servers.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744984275a4604517.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信