Cross domain xmlhttp
I am writing this javascript that will be used on several other domains which calls a php script(only on my domain) to return an array. I am using xmlhttp and it works great when testing on my domain, but as soon as the javascript is placed or called from a separate domain it completely breaks. Anybody know how to make this request cross-domain?
Note: I had to perform a weird little hack to allow me to make two separate calls and make sure that they were both returned before processing. Anyways this does work perfectly every time on my domain.
This is tin the javascript file that calls my php code for the array
function getUrls(){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp2 = new XMLHttpRequest();
}
else {
// code for IE5 and IE6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// code for IE5 and IE6
xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
parsedJSONurls = JSON.parse(xmlhttp.responseText);
xmlhttp2.open("GET", "http://mydomain.com/connect.php?q=companies", true);
xmlhttp2.开发者_如何学JAVAsend();
}
}
xmlhttp2.onreadystatechange = function(){
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
parsedJSONcompanies = JSON.parse(xmlhttp2.responseText);
runLoop(parsedJSONurls, parsedJSONcompanies);
}
}
xmlhttp.open("GET", "http://mydomain.com/connect.php?q=urls", true);
xmlhttp.send();
}
Try adding this header to your connect.php file
header('Access-Control-Allow-Origin: http://domain1.com, http://domain2.com');
If you want to permit all domains instead of a whitelist
header('Access-Control-Allow-Origin: *');
https://developer.mozilla.org/en/http_access_control
The reason for this is the same origin policy. It was put in place to stop malicious scripts from accessing sensitive data from other websites. You should look into writing a JSONP request as a workaround for your problem.
There's an ongoing community wiki I started last year that explains many ways of circumventing the same origin policy. A solution that fits your situation can most likely be found there.
Same with others, it's caused by same origin policy.
Suppose page is at "a.com", no matter where JavaScript file is,
As long as you use XMLHttpRequest approach, you can only access data from a.com.
Even subdomain a.a.com can't access a.com.
You can have 2 options:
1) Use <script/> tag hack
JSONP is great, but it seems you don't rely on any library.
It's a JavaScript nature you can include JavaScript locating on other domain.
<script/> tag hack is a simple technique which dynamically create and append <script/> node.
And its src attribute is the URL which is in different domain.
function getUrl(url) {
var scriptEl = document.createElement("script");
scriptEl.src = url;
scriptEl.async = true;
document.getElementsByTagName("head")[0].appendChild(scriptEl);
}
// Predefined callbacks
window.companyCallback = function (responseData) {
parsedJSONCompanies = responseData;
};
window.urlCallback = function (responseData) {
parseJSONurls = responseData;
};
getUrl("http://mydomain.com/connect.php?q=companies");
getUrl("http://mydomain.com/connect.php?q=urls");
Of course you also have to modify your PHP to meet the need.
<?php
header("content-type: application/json");
if ($_GET['q'] === "urls")
{
echo "companyCallback(";
json_encode($result);
echo ");";
}
else
{
echo "urlCallback(";
json_encode($result);
echo ");";
}
?>
2) Place proxy.php in different domain
The above method is what I recommended.
If you don't want to revamp your code heavily, use proxy technique instead.
You must have privilege to add a proxy.php on different hosts.
The content like this:
<?php
$url = "http://mydomain.com/connect.php?q=" . $_GET["q"];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
?>
NOTE: Be careful about security issue, you need to check where the request from.
In JavaScript, you just need to point the url in xmlhttp.open() to this same domain PHP.
xmlhttp.open("proxy.php?q=urls", true);
Hope it helps.
Like others said you could use JSON-p) for that or if the browsers supports(new A-graded browsers do) CORS you could use that instead.
As mentioned most non html5 dont allow cross browser ajax requests. To get around this I call a remote javascript script.
use javascript to add a line like
<script type="text/javascript" src="http://www.somemedomain.xxx/myjavascript.php?arg1=xxx&arg">
on the myjavascript.php file on the other server, you can process, collect information collected from the browser.
you have to encode the php file as javascript.
header( "content-type: application/javascript" ) //check php.net
This will work in ie6+
精彩评论