{{js跨域请求解决方案续}}Cross-domain XMLHttpRequest(使用Apache mod_rewrite实现跨域请求)

The other day I was trying some cross-domainXMLHttpRequeststuff. As you probably know, XMLHttpRequest doesn’t work well across domains. (I was testing it locally; with all the coolness, domain restrictions didn’t hit me once.) The solutions is simple—mod_rewrite. I’m not sure if there are docs that talk about this, so I thought it’d be useful to put together this mini how-to. (If you know about the cross-domain issues, you might want to dive to the last section.)

Cross-domain?

Before we get into any of that, following is an example set of functions that would typically form your XMLHttpRequest workhorse »

function getXmlHttpObject(){
	if (window.XMLHttpRequest)
		return new XMLHttpRequest();
	else if (window.ActiveXObject)
		return new ActiveXObject("Microsoft.XMLHTTP");
	else {
		alert("XMLHttpRequest not supported!");
		return null;
	}
}

function handleHttpResponse() {
	if (http.readyState == 4) {
		results = http.responseText;
		alert(results);
	}
}

function doSomeStuff() {
	var post_arg1 = document.my_form.post_arg1.value;
	var post_arg2 = document.my_form.post_arg2.value;
	var post_url = 'http://yahoo.com/form_do'
	post_data = 'post_arg1=' + post_arg1 + '&post_arg2=' + post_arg2;
	http.open("POST", post_url);
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	http.send(post_data);
	http.onreadystatechange = handleHttpResponse;
	return false;
}

var http = getXmlHttpObject();

I’m not going to get into the not-so-gory details of XMLHttpRequest (Ajax, or whatever), there’stonsofplacesyou’ll find good information. (I particularly recommend the last link if you’re new to all this stuff.)

So, getting back on track, the whole point of putting up those lines of code was to illustrate what “cross-domain” means. The last of the three functions that you see is the one that would be called to perform the action. Assume that the above script is within an HTML file, whose URL is, say:

http://premshree.org/form

So, some action (onBlur,onClick,onSubmit, etc.) inform(resides onpremshree.org) triggersdoSomeStuff(), which in turn makes an XMLHttpRequest request toform_do, which resides on another domain (</tt>yahoo.com</tt>).

Notice the mismatch between the domains of the location of our HTML file (form) and the file that does the action (form_do)? That domain mismatch is precisely what cross-domain is.

XMLHttpRequest is insanely awesome. However, it has domain restrictions. That is, both files—the file where the call is being made, and the file to which the call is being made—need to be within the same domain.

Hold on, cross-domain XMLHttpRequest works... kinda

Actually, cross-domain requests are handled in their own different ways byMSIEand Mozilla. Youcando cross-domain requests in MSIE; however, this involves changing its default security settings, or by adding certain hosts to your “trusted hosts” list. Quoting fromhere:

...
This is how cross-domain security fundamentally works. It's far from a perfect system, but it's simple. Since there is no way to specify which pages trust other pages to access their data, Internet Explorer simply says that if two pages are not in the same domain, they cannot communicate. More precisely, Zone Manager (found on the security tab in Internet Settings) does allow the user to say that a page may access another page, but as you point out, most people leave it set on prompt. You can suggest users add the page to the trusted site zone, or merely say Yes to the dialog box.
...

Mozilla, on the other hand, has the concept ofsigned scripts. You need to enable one or more of theUniversalBrowser*privileges, depending on the different domains involved in the cross-domain request. For example, if you’re accessing a remote host from your local file system—that is, accessinghttp://files fromfile://—you need to enableUniversalBrowserReadprivilege.

Nah, screw it

The reality of the situation is that cross-domain XMLHttpRequest doesn’t work as well as we would want it to on the browsers that we deeply care about, unless, of course, you are insane enough to be willing unsuspecting, naïve users to deal with things like signed scripts and trusted hosts.

Is there a solution?

Yes, thanks to somemod_rewritemagic. All we need is theRewriteRuledirective.

The configuration changes need to be made to the configuration file (typicallyhttpd.conf) of the Apache server that serves the file that makes the request (form, in our example; that is, the server thatpremshree.orgruns on). Here are the steps involved:

  • First,Apachemust be configured with proxy enabled »

    ./configure --enable-proxy

  • Make sureRewriteEngineis enabled »

    RewriteEngine on

  • Add the following rule »

    RewriteRule ^/form_do$ http://yahoo.com/form_do [P]

    ThePflag that you see there indicates apass-through proxy.

    So now instead of requestinghttp://yahoo.com/form_do(see bold line in the code; I knew those lines of code would be kinda useful), request for/form_do. So our request code will look like this »

    var post_url = '/form_do';

    That’s it, you’re done.

So there, a solution that cares a damn about the browser you’re using.

Caveat

Note that when you do something like this—dealing with proxies—you need to be very careful about security issues. I’m not terribly good at this, so I’m afraid I might not be able to answer your questions concerning those issues.

Many thanks toGopalfor lot of the information.

Edit [2005-11-21 10:13]:Jason Lewitthas an articleon ways to get get around cross-domain XMLHttpRequest. One of them is the pass-through proxy that I discussed here.

你可能感兴趣的:(XMLhttpREquest)