Home >Backend Development >PHP Problem >Ajax request error, how to enable cross-domain request in PHP
This article will introduce to you how to report an ajax request error and enable cross-domain requests in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Add
header("Access-Control-Allow-Origin: *");
If you want to To allow only a certain website to pass, you can set
header("Access-Control-Allow-Origin: http://test.com"); // Allow cross-domain requests initiated by test.com, Others will not pass
If it is a php framework, it needs to be placed after the namespace, not in front, otherwise an error will be reported
<?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); ?>
<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>
Recommended learning: php video tutorial
The above is the detailed content of Ajax request error, how to enable cross-domain request in PHP. For more information, please follow other related articles on the PHP Chinese website!