前后端分离,多域名,CORS跨域解决方案
后台代码:
//多域名-CORS跨域方案-服务端
$allowOrigin = array('http://www.logindemo.com','http://www.newweb.com','https://www.baidu.com');
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
if(in_array($origin,$allowOrigin)){
header('Access-Control-Allow-Origin:'.$origin);
}
header('Access-Control-Allow-Headers:Origin,X-Requested-With,Content-Type,Accept,Authorization,Cookie');
header('Access-Control-Allow-Methods:GET,POST');
前台代码:
js文件:
$("#submit").click(function() {
$("#request-process-patent").html("正在提交数据,请勿关闭当前窗口...");
$.ajax({
type: "POST",
url: "http://www.newweb.com/index.php?act=loginWap&op=login",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(GetJsonData()),
dataType: "json",
success: function (data) {
if (data.code == 200) {
alert('登录成功!');
window.location.href="http://www.logindemo.com/backend.html";
}else {
alert('用户名或密码错误!');
}
},
error: function (message) {
$("#request-process-patent").html("用户名或密码错误!");
}
});
});
function GetJsonData() {
var json = {
"code": $("#code").val(),
"user_name": $("#user_name").val(),
"password": $("#password").val()
};
return json;
}
HTML文件:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/login.js" ></script>
<title>手机登录</title>
<script type="text/javascript" src="/js/jquery.min.js"></script>
</head><body><h3>用户登录</h3><br />
用户名:<input id="user_name" type="text" name="user_name" value="" /><br /><br />
密 码:<input id="password" type="password" name="password" value="" /><br /><br />
<button id="submit" value="submit">登录</button>
</body>
</html>
网友评论