Home  >  Article  >  Backend Development  >  How PHP+AJAX realizes cross-domain

How PHP+AJAX realizes cross-domain

高洛峰
高洛峰Original
2017-02-08 13:17:211544browse

PHP file code [I am using PHPCMS as an example]

Add a mobile folder [module] under the phpcms\modules folder; add an index.php file under the module, The code is as follows:


/**
public function test()
{
//Load database model
$mb_start_db = pc_base::load_model('mb_start_model');
$where = array('id'=> 1);
$data = ('pic1,pic2,pic3');
$res = $mb_start_db->get_one($where, $data);

if($res)
                                                                                                                                                                                                                                                   if(!empty($_GET['callback'])) result'=>$res);
                                                                                       echo $_GET['callback']. '('.json_encode($json_arr).')'; ('status'=>1,'msg'=>'Success!','result'=>$res);
          echo json_encode($json_arr);die;
      }
      }

}
This is a complete code
**/


Note: The above code has a $_GET['callback'] , this is a parameter of jsonp;

Look at the code of the HTML5 page:

##The final rendering is as follows:

How PHP+AJAX realizes cross-domain

But if you click the Get Data button [Note: The name of the button should be Get Data, sorry for the typo], the following error will appear:

How PHP+AJAX realizes cross-domain

This error is not allowed, or cross-domain is prohibited. The solution is very simple. Add a piece of code to the head of the PHP file:

How PHP+AJAX realizes cross-domain

/ **

header("Access-Control-Allow-Origin:*");

* indicates that all domain names can be accessed
**/


After adding the above code, the final effect is as follows:


If dataType:'jsonp', Look at the PHP code in the picture below

How PHP+AJAX realizes cross-domain

:

How PHP+AJAX realizes cross-domain

The result is as follows:

How PHP+AJAX realizes cross-domain

Briefly summarize 2 points:

1. Use jsonp when making Ajax requests, and then also bring jsonp data when receiving and returning from PHP; How PHP+AJAX realizes cross-domain

2. Only provided to To use a browser that supports HTML5, you only need to add the following two sentences to the header of PHP

header("Access-Control-Allow-Origin:*"); //* means all Domain names can be accessed

header("Access-Control-Allow-Method:POST,GET");

For more articles related to how PHP+AJAX achieves cross-domain implementation, please pay attention to the PHP Chinese website!

Statement:
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