两个不同域名的程序在处理ajax的时候肯定会有跨域的存在,一种方式是通过jsonp,一种是通过请求本域名,然后后端PHP转发curl,还有一种比较简单 通过header头来实现,例如
现在有两个域名 和 在下面请求下面的Php文件。
<!DOCTYPE HTML>
<html lang="en-US"><head>
<meta charset="UTF-8">
<title></title>
<script src="http:///jquery/2.2.4/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
$(function(){
$.post("http:///test.php",{"name":"lizhaoyao","sex":"man"},function(res){
console.log(res);
},"json");
});
</script>
</body>
</html>
一个很简单的ajax请求,传送 name 和sex 该文件这样写
<?php
$ret = array(
'name' => isset($_POST['name'])? $_POST['name'] : '',
'sex' => isset($_POST['sex'])? $_POST['sex'] : ''
);
echo json_encode($ret);
?>
然后通常情况下会出现一个跨域提醒
XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'The response had HTTP status code 404.
然后我们可以加一段代码
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
header('content-type:application:json;charset=utf8');
header('Access-Control-Allow-Origin:'.$origin);
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
如图:
<?php
$ret = array(
'name' => isset($_POST['name'])? $_POST['name'] : '',
'sex' => isset($_POST['sex'])? $_POST['sex'] : ''
);
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
header('content-type:application:json;charset=utf8');
header('Access-Control-Allow-Origin:'.$origin);
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
echo json_encode($ret);
exit();
再看效果
xhr请求成功!