Home >Backend Development >PHP Tutorial >A brief discussion on cross-domain issues in PHP
The content of this article is about the cross-domain issues of PHP. Now I will share it with you. Friends in need can refer to it
Let’s talk about the simplest example first
First The code on the server
public function kuayu(){ header("Access-Control-Allow-Origin: http://baidu.com"); //说明是允许百度访问你的服务器 return json(['status'=>0,'msg'=>1231]); }
Access-Control-Allow-Origin:加上你请求该服务器的域名
如果要允许所有的服务器访问的话就只需要一个*,例如Access-Control-Allow-Origin:*
Finally the code on the client
$.ajax({ url:'http://xxx.com/kuayu',这里填写你所访问的链接 async:false, success:function(res){ console.log(res); } })
最后就完成了简单的跨域请求
Let’s briefly talk about jsonp cross-domain (due to the blogger’s theory I don’t have solid knowledge, so I can only post the code, haha)
First go to the server-side code
public function kuayu(){ return input('get.callback')."(".json_encode(['status'=>0,'msg'=>1231]).")"; }
Client-side code
$.ajax({ url:'http://www.xx.cn/kuayu', dataType:'jsonp',固定写法 jsonp:'callback',固定写法 success:function(res){ console.log(res); } })
There is a pitfall in this, that is, the server returns The format of the data must be as follows
jQuery111307920822086038766_1523501176244({"status":0,"msg":1231})
The big string in front is generated by the system, or it can be customized
So the return data from the server must be $_GET['callback']. (Data) This format is like this
Related recommendations:
PHP cross-domain Ajax solution
How to use php cross-domain cookie sharing _PHP tutorial
The above is the detailed content of A brief discussion on cross-domain issues in PHP. For more information, please follow other related articles on the PHP Chinese website!