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

醉折花枝作酒筹
Release: 2023-03-09 20:18:02
forward
2222 people have browsed it

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);
 ?>
Copy after login

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>
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template