简体   繁体   中英

Send javascript Object through $.ajax

I want to send a javascript object like this one through a $.ajax request :

 var o = {
   a: 1, 
   b: 'dummy string', 
   c: ['a', 1, {}], 
   d: {dd: 1}, 
   e: new Date(), 
   f: function() {
        console.log('here');
   }
}

I know that i normally should use JSON.stringify before sending it to my php script. The problem is JSON.stringify, removes the properties it can't stringify :

JSON.stringify(o);

returns this ->

"{
  "a":1,
  "b":"dummy string",
  "c":["a",1,{}],
  "d":{"dd":1},
  "e":"2015-11-13T21:34:36.667Z"
}"

But what shoud i do, if i want to store in a mysql column the "o" javascript object as plain text like this :

o = {
   a: 1, 
   b: 'dummy string', 
   c: ['a', 1, {}], 
   d: {dd: 1}, 
   e: new Date(), 
   f: function() {
        console.log('here');
   }
}

You could try this:

var o = {
   a: 1, 
   b: 'dummy string', 
   c: ['a', 1, {}], 
   d: {dd: 1}, 
   e: new Date(), 
   f: function() {
        console.log('here');
   }
};

o.f = o.f.toString();
var stringy = JSON.stringify(o);
document.getElementById('test2').innerHTML = stringy;

Fiddle: http://jsfiddle.net/e2cxandt/

Obviously this needs to be changed a bit so you aren't overwriting the function by maybe cloning the object but as a quick example you can see it now has the property in the string.

As someone mentioned in the comments above, war10ck, here is an example of using the replacer argument of JSON.stringify

var o = {
   a: 1, 
   b: 'dummy string', 
   c: ['a', 1, {}], 
   d: {dd: 1}, 
   e: new Date(), 
   f: function() {
        console.log('here');
   }
};

function replacer (key, value) {
  if (typeof value === "function") {
    return value.toString();
  }
  return value;
}

var stringy2 = JSON.stringify(o, replacer);
document.getElementById('test2').innerHTML = stringy2;

Fiddle: http://jsfiddle.net/e2cxandt/1/

a couple universal (non-specific-instance) options:

you can define a custon toJSON on any object:

Function.prototype.toJSON=function(){return String(this);}; 

JSON.stringify({a:1, b:function(){alert(123)}});

which shows:

{"a":1,"b":"function (){alert(123)}"}

the one caveat is that your function literal is quoted as a string and no longer a function. to fix that if needed, you can use a reviver parameter to JSON.parse().

a better option: using a replace arg to JSON.stringify() :

JSON.stringify({a:1, b:function(){alert(123)}}, function(k,v){
  if(typeof v==="function") return String(v);
  return v;
});

which shows:

{"a":1,"b":"function (){alert(123)}"}

that way is particularly nice because you need not modify an built-in or instance objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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