【发布时间】:2013-03-15 22:47:11
【问题描述】:
这是我编写的一个函数和助手,用于序列化 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;
}
【问题讨论】:
-
假设你不需要支持IE
-
我在向服务器发送 JSON 编码字符串时遇到的问题是存储在 JSON 中的每个 uri-component-encode 编码值都由我的服务器自动解码,这不是个别变量的问题,因为我可以重新编码数据服务器端,但如果它全部在 JSON 字符串中;好吧,我无法对整个字符串进行编码,因此数据基本上丢失了。但也许我应该考虑使用 XHL 库;我研究了 moo-tools,这似乎很容易使用。
-
+1 用于 Mootools,尽管几乎每个库都将 XHR 请求抽象为更易于使用的界面。
标签: javascript ajax json serialization