The server solves the cross-domain problem of the front-end JS Ajax request:
Method 1: Add the following code to the PHP code (* asterisks cannot have spaces, and are added to the bottom code)
header("Access-Control-Allow-Origin:*");
/** 例:用于H5充值页面查询用户信息
* /api/hpay/getUserInfo?username=18857xxxx25
*/
function getUserInfo(){
header("Access-Control-Allow-Origin:*"); //一行代码搞定Ajax跨域问题
$mobile = input('username','','trim');
if(empty($mobile)){
$this->toJson('请输入手机号.',0,[]);
}
if((strlen($mobile)!=11)){
$this->toJson('你输入的手机号有误.',0,[]);
}
$find = M('user')->field('user_name,u_pic,nick_name')->where(['mobile'=>$mobile])->find();
if(!$find){
$this->toJson('手机号有误或不存在.');
}
$this->toJson('查询成功.',1,$find);
}
Method 2: nginx configuration allows cross-domain requests
add_header Access-Control-Allow-Origin *;
#add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
#add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
If there is still a JS error report, the page jumps to report an error, for example: This request has been blocked; the content must be served over HTTPS
Reason for error report:
caused by the mixture of http and https
The website uses https to jump to http request, which is blocked.
Solution:
1. All pages use https, or all use http
2. If https has been configured, you can add the following code in the meta tag of <head>
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"/>
It means to automatically upgrade all insecure http requests to https requests
The recommended method of use has been tested by myself, and all browsers are OK. . .