HTML代码
<html>
<head>
<title>跨域测试</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function () {
$("#btn").click(function () {
$.ajax({
dataType: "jsonp",
url: "http://www.xx.com/xx/index.php",
//jsonp: "callback",
//jsonpCallback:"success_jsonpCallback",
success: function(data) {
console.log(data);
var json = eval('(' + data + ')');
$("#text").text("uid:" + json.uid + " name:" + json.name);
},
error:function(){
alert('fail');
}
});
});
});
</script>
</head>
<body>
<input id="btn" type="button" value="跨域获取数据" />
<textarea id="text" style="width: 400px; height: 100px;"></textarea>
</body>
</html>
PHP 代码
$callback = Yii::$app->request->get('callback');
if(!empty($callback)) {
$data = json_encode(array('uid' => 1,'name' => '测试',),JSON_UNESCAPED_UNICODE);
echo $callback.'('.json_encode($data).')';
}
或者,服务器端,相关方法内,加入
$request = Yii::$app->response;
$request->headers->add('Access-Control-Allow-Origin','*');
$request->headers->add('Access-Control-Allow-Credentials','true');
$request->headers->add('Access-Control-Allow-Methods','GET, POST, OPTIONS');
$request->headers->add('Access-Control-Allow-Headers','x-requested-with,content-type,test-token,test-sessid');