Home >Backend Development >PHP Problem >Ajax request error, how to enable cross-domain request in PHP

Ajax request error, how to enable cross-domain request in PHP

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-05-21 17:32:572210browse

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.

Ajax request error, how to enable cross-domain request in PHP

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

<?php 
	header(&#39;Access-Control-Allow-Origin: *&#39;);
	$arr = [
		array(&#39;id&#39;=>1,&#39;title&#39;=>&#39;one1&#39;),
		array(&#39;id&#39;=>2,&#39;title&#39;=>&#39;one2&#39;),
		array(&#39;id&#39;=>3,&#39;title&#39;=>&#39;one3&#39;),
		array(&#39;id&#39;=>4,&#39;title&#39;=>&#39;one4&#39;),
	];

	echo json_encode($arr);
 ?>

index.html

<script type="text/javascript" src="jq.js"></script>
<script type="text/javascript">
	$.ajax({
		type:&#39;post&#39;,
		url: &#39;http://127.0.0.1/demo1/api.php&#39;,
		contentType: "application/x-www-form-urlencoded",
		dataType: &#39;json&#39;,
		success: function(res){
			console.log(res)
		}
	})
</script>

Ajax request error, how to enable cross-domain request in PHP

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete