ObjectToQuery函数返回只是属性值,但我想要所有的属性
ObjectToQuery function return just the properties have values but i want all the properties
我使用此方法是为了将对象转换为QueryString。
QueryString是ajax
发送请求所必需的。
var objectToQueryString = function(a) {
var prefix, s, add, name, r20, output;
s = [];
r20 = /%20/g;
add = function(key, value) {
// If value is a function, invoke it and return its value
value = (typeof value == 'function') ? value() : (value == null ? "" : value);
s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
};
if (a instanceof Array) {
for (name in a) {
add(name, a[name]);
}
} else {
for (prefix in a) {
buildParams(prefix, a[prefix], add);
}
}
output = s.join("&").replace(r20, "+");
return output;
};
function buildParams(prefix, obj, add) {
var name, i, l, rbracket;
rbracket = /'[']$/;
if (obj instanceof Array) {
for (i = 0, l = obj.length; i < l; i++) {
if (rbracket.test(prefix)) {
add(prefix, obj[i]);
} else {
buildParams(prefix + "%" + (typeof obj[i] === "object" ? i : "") + "%", obj[i], add);
}
}
} else if (typeof obj == "object") {
// Serialize object item.
for (name in obj) {
buildParams(prefix + "%" + name + "%", obj[name], add);
}
} else {
// Serialize scalar item.
add(prefix, obj);
}
}
下面的代码成功地将对象转换为QueryString,但是没有值的属性在返回QueryString中被省略。
但是我想要对象的所有属性。对象属性是否有值并不重要
如果您传递的属性值为null
,则此调用中的'obj'参数将为null
:
function buildParams(prefix, obj, add) {
你可以测试你的结果,当你改变你的'buildParams'函数:
function buildParams(prefix, obj, add) {
obj = obj || "";
var name, i, l, rbracket;
rbracket = /'[']$/;
if (obj instanceof Array) {
for (i = 0, l = obj.length; i < l; i++) {
if (rbracket.test(prefix)) {
add(prefix, obj[i]);
} else {
buildParams(prefix + "%" + (typeof obj[i] === "object" ? i : "") + "%", obj[i], add);
}
}
} else if (typeof obj == "object") {
// Serialize object item.
for (name in obj) {
buildParams(prefix + "%" + name + "%", obj[name], add);
}
} else {
// Serialize scalar item.
add(prefix, obj);
}
}
相关文章:
- 在多行图表中,在每一行的末尾,我想要一个小圆圈和使用d3.js的端点值
- 我想要相同的函数以两种方式反应
- 如何在javascript中创建一个空的2d数组?下面是我想要创建的一个示例
- 如何用javascript发送多个文件没有jQuery我想要每个文件一个进度条
- 我想要一个类似于网站 https://onlycoin.com/ 的jQuery鼠标滚动动画效果
- 我想要“鼠标滚轮事件延迟”
- 如何格式化我返回的url,使其符合我想要的路由
- 如何使用facet指定我想要的字段
- json_encode($myVar);正在给出地图,我想要一个字符串数组
- 我想要输入类型<输入>在javascript中
- Javascript:我可以't找到正确的方式来表达布尔“;如果“;以得到我想要的结果
- 如何用javascript从数组中删除项?我想要一个类似拉的东西来做与推相反的事情
- 正则表达式对我想要做的事情是正确的吗?
- Javascript给定了一个数字,我想要所有可能的组合和元素数组
- 为什么获胜't我的javascript返回我想要的值
- 我想要获取文件输入并将其保存到本地路径的Javascript
- .remove() 只删除内部 HTML,而不是像我想要的那样删除整个标签
- 当我想要设置对象属性时,输入中的未定义值
- 我如何通过另一个对象访问一个对象,这个对象包含一个对象,这个对象是我想要访问的对象的属性
- ObjectToQuery函数返回只是属性值,但我想要所有的属性