我有一个代理,我想代理ajax
请求,我已经找到该代码,并且效果很好:
(function() {
if (window.XMLHttpRequest) {
function parseURI(url) {
var m = String(url).replace(/^\s+|\s+$/g, "").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
// authority = "//" + user + ":" + pass "@" + hostname + ":" port
return (m ? {
href : m[0] || "",
protocol : m[1] || "",
authority: m[2] || "",
host : m[3] || "",
hostname : m[4] || "",
port : m[5] || "",
pathname : m[6] || "",
search : m[7] || "",
hash : m[8] || ""
} : null);
}
function rel2abs(base, href) { // RFC 3986
function removeDotSegments(input) {
var output = [];
input.replace(/^(\.\.?(\/|$))+/, "")
.replace(/\/(\.(\/|$))+/g, "/")
.replace(/\/\.\.$/, "/../")
.replace(/\/?[^\/]*/g, function (p) {
if (p === "/..") {
output.pop();
} else {
output.push(p);
}
});
return output.join("").replace(/^\//, input.charAt(0) === "/" ? "/" : "");
}
href = parseURI(href || "");
base = parseURI(base || "");
return !href || !base ? null : (href.protocol || base.protocol) +
(href.protocol || href.authority ? href.authority : base.authority) +
removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === "/" ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? "/" : "") + base.pathname.slice(0, base.pathname.lastIndexOf("/") + 1) + href.pathname) : base.pathname)) +
(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
href.hash;
}
var proxied = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
if (arguments[1] !== null && arguments[1] !== undefined) {
var url = arguments[1];
url = rel2abs("' . $url . '", url);
url = "' . PROXY_PREFIX . '" + url;
arguments[1] = url;
}
return proxied.apply(this, [].slice.call(arguments));
};
}
})();
但是问题是我也有一些
ajax
请求,我不需要proxyify
,但是我也使用XMLHttpRequest
...问题是我该如何过滤我的
ajax
请求并在该javascript
中忽略它们? 最佳答案
添加一个公共接口来访问代理的open
调用:
var proxied = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open_noproxy = proxied;
然后,当您要进行普通的AJAX调用时,可以调用
XMLHttpRequest::open_noproxy()
。另一种方法是在网址中添加关键字,例如
NOPROXY:http://whatever
。您替换的open
函数可以检查URL是否以NOPROXY:
开头;如果是这样,它将从URL中删除它,然后在调用proxied
之前跳过添加代理前缀的代码。关于javascript - 通过代理过滤ajax请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23964563/