浏览器是拒绝跨域请求的,通常解决跨域会采用JSONP(JSON with Padding)和CORS(Cross-Origin Resource Sharing).
环境
8082
目录/var/www/exercise2
192.168.170.199:8082
下index.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js">
</script>
<!--
<script type="text/javascript" src="http://192.168.170.199:8081/exercise/jsonp.php?callback=jsonpCallback"></script>
-->
<script type="text/javascript">
function jsonpCallback(data) {
console.log(data);
}
function remote() {
$.ajax({
url: "http://192.168.170.199:8081/exercise/jsonp.php",
dataType: "jsonp",
jsonpCallback: "jsonpCallback",
success: function(data) {
console.log("[*] Success: " + data);
}
});
}
jQuery(document).ready(function(){
remote();
});
</script>
</head>
</body>
</html>
启动
php -S 0.0.0.0:8082
8081
目录/var/www/exercise
192.168.170.199:8081
下jsonp.php
<?php
header('content-type: application/json; charset=utf-8');
$data = array('first'=>'Qiqi', 'last'=> 'Cai');
echo $_GET['callback'].'('.json_encode($data).')';
?>
Demo
参考
http://www.ruanyifeng.com/blog/2011/01/json_in_php.html
http://blog.knownsec.com/2015/03/jsonp_security_technic/