2013-03-15 22 views
1

這是我編寫的一個函數和幫助程序,用於序列化一個JavaScript對象,用於發送ajax請求。有可能是在某處有更高效的解決方案,可能在jQuery庫中,但我找不到一個解決方案。沒有一個JavaScript對象。爲ajax請求序列化javascript對象的遞歸函數 - 有沒有更簡單的方法?

/* 
@author Benjamin Yep 
@important - THIS FUNCTION ASSUMES INPUT ENCODED ACCORDING RFC 3986 see here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent 
@param data - Any javascript object or array. 
@param pName - The name of the object to be sent in your ajax request. 
@return A serialized JSON-encoded object, ready to send in a request. 
Usage: 
var someObject={ 
"foo":"bar", 
"bars":["foo","bar"], 
"object":{ 
    "foo":1, 
    "bar":2", 
}, 
}; 
var r=makeHttpObject();//new ajax object 
r.open("get","example.php",false); 
r.send(paramify(someObject,"varname")); 
//In example.php 
<?php 
echo var_dump($_POST['varname']); 
?> 
//back in the javascript file 
console.log(r.responseText);//shows the contents of the object you sent to the server 
*/ 
function paramify(data,pName){ 
return constructObject(data,pName).substr(1); 
} 
function constructObject(data,path){ 
var contents=""; 
for(var key in data){ 
    var curpath=path+"["+key+"]"; 
    if(Object.prototype.toString.call(data[key])==='[object Object]'||data[key] instanceof Array){ 
     if(!(data[key] instanceof Array)||data[key].length!=0){ 
      if(JSON.stringify(data[key])=="{}"){ 
       contents+="&"+curpath+"={}"; 
      }else{ 
       contents+=constructObject(data[key],curpath); 
      } 
     }else{ 
      contents+="&"+curpath+"=[]"; 
     } 
    } 
    else{ 
     contents+="&"+curpath+"="+data[key]; 
    } 
} 
return contents; 
} 
+1

假設你不需要支持IE <8,您可以使用JSON.stringify。此外,許多xhr庫將接受一個普通的javascript對象(不是JSON字符串)併爲您處理編碼。 – 2013-03-15 22:59:26

+0

我向服務器發送JSON編碼字符串時遇到的問題是,存儲在JSON中的每個uri-component-encode編碼值都會被我的服務器自動解碼,這不是個別變量的問題,因爲我可以只需重新編碼數據服務器端,但是如果它全部位於JSON字符串中;好吧,我不能編碼整個字符串,所以數據基本上丟失了。 但也許我應該看看使用XHL庫;我研究了moo-tools,這看起來很容易使用。 – 2013-03-16 00:55:52

+0

+1對於Mootools,儘管幾乎每個庫都將XHR請求抽象爲易於使用的界面。 – 2013-03-17 02:12:51

回答

1

就效率而言,這種功能並沒有太多的改進。

但是,您應該能夠在您的函數中同等對待對象和數組。使用數字鍵,for...in循環可以正常工作。

此外,還要確保你的一切編碼進入的輸出與encodeURIComponent()

+0

謝謝,我會盡快完成這些修改。 – 2013-03-16 01:05:00

-1

請看這個插件

jquery json

此插件公開四個新方法到(根)jQuery對象:

的toJSON:序列化javascript對象,數量字符串或數組轉換爲 JSON。

evalJSON:快速地從JSON轉換爲Javascript,並且很簡單。

secureEvalJSON:從JSON爲Javascript轉換,但這樣做的同時 檢查,看看是否源實際上是JSON,而不是拋出其他 JavaScript語句

quoteString:地方轉轉字符串引號,和智能地逃脫 任何報價,反斜槓或控制字符。

+0

他正在尋找一種方法將其編碼爲查詢字符串,而不是json。 – 2013-03-15 23:12:53

相關問題