不要使用.encodeURIComponent()
編碼查詢參數,不要你;它可能有無效的網址字符(特殊字符等)給你一個頭像。試試這個函數,你可以使用它來進行對象 - >查詢字符串轉換(如果你將json objs存儲在存儲器中),它也可以用於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, '+');
}