您不使用.encodeURIComponent()
对查询参数进行编码,不是吗?它可能包含无效的 url 字符(特殊字符等),让您头疼。试试这个功能,你可以将它用于对象 -> 查询字符串转换(如果你将 json objs 存储在 storage 中),它也适用于 key=value 对。对于单个查询参数.encodeURIComponent()
的工作...
function uriParamNcoder(obj) {
if (
Object.prototype.toString.call(obj) === "[object String]"
) {
return obj.split('=')
.map(
function (part) {
return encodeURIComponent(part);
}
)
.join('=')
.replace(/%20/g, '+');
}
var q_str_arr = [];
objTrace(
obj,
function (k, v, trace) {
var tmp = trace.match(/^\[(.+?)\](.*)$/);
q_str_arr.push(
encodeURIComponent(tmp[1]) +
((tmp[2] !== void 0) ? encodeURIComponent(tmp[2]) : "") + "=" + encodeURIComponent(v)
);
}
);
function objTrace(obj, fn) {
if (
obj === Object(obj) && (typeof fn === "function")
) {
objParamTracer.apply(
obj, [obj, fn].concat(Array.prototype.slice.call(arguments, 2))
);
}
return obj;
}
function objParamTracer(obj, fn, trace) {
trace || (trace = "");
if (
Object.prototype.toString.call(obj) === "[object Array]"
) {
obj.forEach(
function (o, k) {
if (o === Object(o)) {
return objParamTracer.apply(
o, [o, fn].concat(trace + "[]")
);
} else {
return fn.apply(
this, [k, o].concat(trace + "[]")
);
}
},
obj
);
} else {
ownEach(
obj,
function (p, o) {
if (
o === Object(o)
) {
return objParamTracer.apply(
obj, [o, fn].concat(trace + "[" + p + "]")
);
} else {
return fn.apply(
this, [p, o].concat(trace + "[" + p + "]")
);
}
}
);
}
}
function ownEach(obj, fn) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
fn.call(obj, prop, obj[prop]);
}
}
return obj;
}
return q_str_arr.join('&').replace(/%20/g, '+');
}