在前端里面,解决跨域的时候总显得那么的恶心,什么jsonp啊,ajax啊,CORS啊什么的,总觉得是在钻空子进行跨域,其实在PHP文件里面只需要加一段代码就可以跨域了,前端你该怎么写还是怎么写,post,get随便用:
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with, content-type');
<?php
// 制定允许其他域名访问
header("Access-Control-Allow-Origin:*");
// 响应类型
header('Access-Control-Allow-Methods:POST');
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with, content-type');
//$callback = isset($_REQUEST['callback']) ? trim($_REQUEST['callback']) : ''; //jsonp回调参数,必需
function getKey($key,$default=""){
return trim(isset($_REQUEST[$key])?$_REQUEST[$key]:$default);
}
$id = getKey("id");
$conn = mysqli_connect("localhost","root","","test") or die("连接失败");
$conn->query("set names utf8");
$sql = "select * from data where ".$id." is not null";
$result = $conn->query($sql);
$arr = [];
while($row=$result->fetch_assoc()){
array_push($arr,json_encode($row));
}
$json = json_encode($arr); //json 数据
print_r($json);