这篇文章将为大家详细讲解有关ajax请求报错php怎么开启跨域请求,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
在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>
什么是ajax
ajax是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术,可以通过在后台与服务器进行少量数据交换,使网页实现异步更新。
关于“ajax请求报错php怎么开启跨域请求”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。