<?php
$ret = array(
'name' => isset($_POST['name'])? $_POST['name'] : '',
'gender' => isset($_POST['gender'])? $_POST['gender'] : ''
);
header('content-type:application:json;charset=utf8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
echo json_encode($ret);
?>
客户端:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title> 跨域测试 </title>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="show"></div>
<script type="text/javascript">
$.post("http://wdphp/ajax.php",{name:"zaho",gender:"male"})
.done(function(data){
document.getElementById("show").innerHTML = data.name + ' ' + data.gender;
});
</script>
</body>
</html>
客户端可以直接放在本地新建一个html文件即可,服务器端随便找个支持PHP的网站根目录下。注意客户端$.post的链接地址改正确即可实现跨域。
主要是看这几句:
header('content-type:application:json;charset=utf8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
header('Access-Control-Allow-Origin:*');