I want to access data from cross domain in website frontend. I have three websites: a.com, b.com and c.com. The site a.com is frontend. The site b.com is backend(API). The c.com is CAS server.
I can directly access the http://b.com/example_test.php on browser. It successfully jump to CAS page to login. Then after login, API returns data.
I want to let a.com to get b.com's data. My code is:
My frontend html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<title>Title</title>
</head>
<body>
<h3 id="article_title"></h3>
<p id="article_text"></p>
</body>
<script type="application/javascript">
var xmlHttpReq = null;
if (window.ActiveXObject) {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
if (xmlHttpReq !== null) {
xmlHttpReq.open("get", "http://b.com/example_test.php");
xmlHttpReq.timeout = 10000;
xmlHttpReq.send("");
xmlHttpReq.onreadystatechange = doResult;
}
function doResult() {
if (xmlHttpReq.readyState === 4) {
console.log(xmlHttpReq.status);
if (xmlHttpReq.status === 200) {
var data = xmlHttpReq.responseText;
var json_data = JSON.parse(data);
/**
do somethin.
*/
}
}
}
</script>
</html>
My backend api example_test.php:
<?php
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:GET,POST,PUT,DELETE,PATCH,HEAD,OPTIONS');
header('Access-Control-Allow-Headers:Origin,Content-Type,Authorization,X-auth-Token');
require_once './MyCAS.php';
$resp = array(
'stats' => -1,
'msg' => 'Empty!'
);
if (array_key_exists('username', $_COOKIE)) {
/**
do something
**/
} else {
phpCAS::client(CAS_VERSION_2_0, "mycase.server.com", 443, "/cas", false);
phpCAS::setNoCasServerValidation();
phpCAS::forceAuthentication();
if (phpCAS::isAuthenticated()) {
$username = phpCAS::getUser();
if ($username !== null) {
$token = md5($username.date('s', time()).date('i', time()));
setcookie('username', $username, time() + 1*86400, '/');
setcookie('token', $token, time() + 1*86400, '/');
/**
do something
**/
}
}
}
?>
But when I access a.com on browser, I it does not jumps to CAS page. I don't understand the problem. Can any one help me to solve this problem?
You can not redirect the caller's request by ajax. One way to achieve it with JavaScript.
PHP example:
<?php
echo 'redirect';
On you HTML JavaScript:
$.ajax({
type: 'POST',
async: false,
url: '/users',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(payload),
success: function(data, textStatus, jqXHR){
if(data == 'redirect'){
console.log(jqXHR.status);
window.location.href= "/thankyou.html";
}
}
});