作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用此方法将对象转换为QueryString。 ajax
发送请求需要 QueryString。
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中省略了没有值的属性。
但我想要该对象的所有属性。对象属性是否有值(value)并不重要。
最佳答案
如果您传递值为 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);
}
}
关于javascript - ObjectToQuery 函数仅返回具有值的属性,但我想要所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33352697/
我使用此方法将对象转换为QueryString。 ajax 发送请求需要 QueryString。 var objectToQueryString = function(a) { var pref
我是一名优秀的程序员,十分优秀!