這是我編寫的一個函數和幫助程序,用於序列化一個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;
}
假設你不需要支持IE <8,您可以使用JSON.stringify。此外,許多xhr庫將接受一個普通的javascript對象(不是JSON字符串)併爲您處理編碼。 – 2013-03-15 22:59:26
我向服務器發送JSON編碼字符串時遇到的問題是,存儲在JSON中的每個uri-component-encode編碼值都會被我的服務器自動解碼,這不是個別變量的問題,因爲我可以只需重新編碼數據服務器端,但是如果它全部位於JSON字符串中;好吧,我不能編碼整個字符串,所以數據基本上丟失了。 但也許我應該看看使用XHL庫;我研究了moo-tools,這看起來很容易使用。 – 2013-03-16 00:55:52
+1對於Mootools,儘管幾乎每個庫都將XHR請求抽象爲易於使用的界面。 – 2013-03-17 02:12:51