繁体   English   中英

通过$ .ajax发送javascript对象

[英]Send javascript Object through $.ajax

我想通过$ .ajax请求发送一个像这样的javascript对象:

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

我知道我通常应该在将其发送到我的PHP脚本之前使用JSON.stringify。 问题是JSON.stringify,删除了无法字符串化的属性:

JSON.stringify(o);

returns this ->

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

但是我应该怎么做,如果我想以纯文本形式将“ o” javascript对象存储在mysql列中,如下所示:

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

您可以尝试以下方法:

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;

小提琴: http//jsfiddle.net/e2cxandt/

显然,这需要进行一些更改,因此您可能不会通过克隆对象来覆盖函数,但是作为一个简单的示例,您可以看到它现在在字符串中具有该属性。

就像上面的评论war10ck中提到的那样,这是一个使用JSON.stringify的replacer参数的示例。

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;

小提琴: http : //jsfiddle.net/e2cxandt/1/

几个通用(非特定实例)选项:

您可以在任何对象上将custon定义为JSON:

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

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

这表现了:

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

一个警告是,您的函数文字被引用为字符串,而不再是函数。 要解决此问题,可以在JSON.parse()中使用reviver参数。

更好的选择:对JSON.stringify()使用replace arg:

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

这表现了:

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

这种方法特别好,因为您不需要修改内置对象或实例对象。

暂无
暂无

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

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