在php文件头部加入
header(“Access-Control-Allow-Origin: *”);
如果想设置只允许某个网站通过的话可以这样设置
header(“Access-Control-Allow-Origin: http://test.com”); // 允许test.com发起的跨域请求,其他的都不通过
如果是php框架的话需要放在namespace后面,而不是前面,否则会报错
*.php
<?php header('Access-Control-Allow-Origin: *');$arr = [array('id'=>1,'title'=>'one1'),array('id'=>2,'title'=>'one2'),array('id'=>3,'title'=>'one3'),array('id'=>4,'title'=>'one4'),];echo json_encode($arr); ?>
index.html
<script type="text/javascript" src="jq.js"></script><script type="text/javascript">$.ajax({type:'post',url: 'http://127.0.0.1/demo1/api.php',contentType: "application/x-www-form-urlencoded",dataType: 'json',success: function(res){console.log(res)}})</script>
推荐学习:php视频教程
以上就是ajax请求报错,php如何开启跨域请求的知识。速戳>>知识兔学习精品课!