这是我编写的一个函数和助手,用于序列化 javascript 对象以在 ajax 请求中发送。有可能在某个地方有更有效的解决方案,可能在 jQuery 库中,但我找不到。不是一个 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;
}