0

Is there a way in jQuery to change $.ajax from defaulting to serializing sent data as a Form to serializing it as JSON?

Instead of the following:

$.post("/my/url/endpoint", JSON.stringify(obj))

I'd like to do something like this once, so that automatically happens:

$.defaultSeralizer = JSON.stringify

From now on I'd be able to:

$.post("/my/url/endpoint", obj)
Chris Pfohl
  • 18,220
  • 9
  • 68
  • 111

2 Answers2

1

You could add a .toJson prototype to the Object that would do it for you. it wouldn't save you a TON of typing but a little depending on what you named it.

Object.prototype.toJson = function(){
   var jsonValue = JSON.stringify(this);
   alert(jsonValue);
}

var person = {"name": "John Smith", "age": 35, "location": "California"};

person.toJson();

Fiddle of it in action

VtoCorleone
  • 16,813
  • 5
  • 37
  • 51
1

No way to do it without really over writing some of the jQuery core, and that will always cause issues down the road. Best option would be to add another ajax helper to jQuery that does what you want.

Here is an example https://stackoverflow.com/a/19516921/823942.

Keep in mind the lack of native JSON support for some browsers.

Community
  • 1
  • 1
Matt R. Wilson
  • 7,268
  • 5
  • 32
  • 48
  • Already have JSON3 pulled in. No worries about JSON support...slow as *#@$ in IE8, but that's how it goes...Thanks. – Chris Pfohl Mar 03 '14 at 03:17