在前端内里,处理跨域的时刻总显得那末的恶心,什么jsonp啊,ajax啊,CORS啊什么的,总觉得是在钻空子举行跨域,其实在PHP文件内里只需要加一段代码就能够跨域了,前端你该怎样写照样怎样写,post,get随意用。
引荐教程:PHP视频教程
PHP处理跨域只需要在PHP文件中到场三个要求头就好了。
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);
以上就是php处理跨域题目的细致内容,更多请关注ki4网别的相干文章!