簡體   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