In the last article, we have mentioned a way to make Ajax requests across subdomains. We now implement a transparent implementation of the developer, which automatically determines whether the request is a cross-domain domain, and if not, uses the traditional method of making Ajax requests, and vice versa.
I've been thinking a lot about how to achieve this executor problem. According to ASP.net Ajax's "standard", you should develop a webrequestexecutor subclass and then set it as the default executor or a specific WebRequest executor. But in the end I used the direct modification of xmlhttpexecutor because of the following reasons:
A full implementation of a webrequestexecutor requires too many interfaces, while Crosssubdomainexecutor and XMLHttpExecutor have too much in common.
If you inherit WebRequestExecutor, you still need to understand the xmlhttpexecutor too much detail, JavaScript can not be too good encapsulation, not to achieve real object-oriented.
The crosssubdomainexecutor behaves exactly the same as xmlhttpexecutor in normal circumstances.
The practice of directly modifying XMLHttpExecutor is to XMLHttpExecutor prototype, which is the usual practice of JavaScript extension objects.
First, we define a static method for the Sys.Net.WebRequest class, which is used to get the domain name from a URL. For example, enter http://www.sample.com/Default.aspx this URL, return http://www.sample.com, this static function is very important to judge whether cross domain, as follows:
Sys.net.webrequest._getrawdomain static method
Sys.Net.WebRequest._getRawDomain = function(url)
{
url = Sys.Net.WebRequest._resolveUrl(url);
var index = url.indexOf('://');
var prefix = url.substring(0, index + 3);
var url = url.substring(index + 3);
index = url.indexOf('/');
if (index < 0)
{
index = url.indexOf('?');
}
if (index >= 0)
{
url = url.substring(0, index);
}
return prefix + url;
}
Second, we extend one for the Sys.Net.WebRequest class to detect whether a request can be sent directly without using our methods. Here we use a XMLHttpRequest object directly as an attempt:
Sys.net.webrequest._checkifiscrossdomainrequest method
Sys.Net.WebRequest.prototype._checkIfIsCrossDomainRequest = function()
{
var request = new XMLHttpRequest();
try
{
request.open('get', this.get_url());
return false;
}
catch(e)
{
return true;
}
}