Home  >  Article  >  Web Front-end  >  How to solve ajax cross-domain problem? (with code)

How to solve ajax cross-domain problem? (with code)

不言
不言Original
2018-08-15 11:22:091436browse

The content of this article is about how to solve the ajax cross-domain problem? (Attached is the code), which has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Use two servers to process the code of a project, one of which only handles interface requests.

Originally, PHP could use CURL for processing, but the leader did not allow PHP to be used to process data. Will affect the functionality of the website. If there is a problem on the interface side, it will cause the entire website or its pages to crash, so the front-end is used to process the data. This problem will not arise.

This article is suitable for programmers who know cross-domain but don’t know what cross-domain is.

Without further ado, PHP programmers, just copy and paste!

var url = "http://xxxxxxx/index.php/Home/index/index?shop_id="+ obj +"";
$.ajax({
      url: url,
      type: "GET",
      dataType: "jsonp",  //指定服务器返回的数据类型
      jsonp:'callback',  //回调函数   设置回调函数后端返回必须带有该函数名,否则获取不到数据 会一直走 error
  //processData: false,                  
      success: function (data) {
      console.log(data);
       },
       error: function (data) {
       console.log("请求数据异常,状态码:" + data.status);
       }
       });

php interface code

public function index()
{
header("Access-Control-Allow-Origin: *"); //允许所有地址访问 可设置访问权限        
header("Access-Control-Allow-Methods:POST,GET");        
header("Access-Control-Allow-Headers:x-requested-with,content-type");        
header("Content-type:text/json;charset=utf-8");
//获取回调函数名,接头暗号  
$callback = I('get.callback');
获取参数  
$aba = I('get.shop_id');//$aa = explode(',',$aba);  
$aaa=[];  
foreach($aa as $v){    
$aaa[]['pageview']= $this->pageview->where(['shop_id'=>$v])->count(); //数据处理  
}
//吐数据    
echo $callback."(".json_encode($aaa).")";
}

Related recommendations:

ajax cross-domain solution, ajax cross-domain

The most comprehensive solution to ajax cross-domain

ajax cross-domain Ajax cross-domain call implementation code using jQuery in PHP

The above is the detailed content of How to solve ajax cross-domain problem? (with code). For more information, please follow other related articles on 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