html代码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="button" value="请求跨域www.tp5.com" onclick="t1();">
</body>
<script type="text/javascript">
function t1(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(this.readyState == 4){
alert(this.responseText);
}
}
xhr.open('get','http://www.tp5.com/public/index',true);
xhr.send(null);
}
</script>
</html>
php代码
<?php
header('Access-Control-Allow-Origin:*'); //*允许所有网站跨域
//header('Access-Control-Allow-Origin:http://localhost'); //*允许指定网站跨域
function index()
{
echo '跨域成功';
}
?>