PHP后台处理jQuery Ajax跨域请求问题 — xx was not called解决办法

// 前台代码
$.ajax({
    url: 'http://www.ushark.net/home/save_trial_apply',
    dataType: 'jsonp',
    processData: false,
    data: $('.layui-layer-content #trialFormInfo').serialize(),
})
.done(function(data) {
    layer.msg('申请成功');
})
.fail(function(jqXHR, textStatus, errorThrown) {
    layer.msg('申请失败,请重试!');
})
.always(function(jqXHR, textStatus, errorThrown) {
    layer.msg('申请成功');
});
// 后台代码(CI框架)
public function save_trial_apply()
{
    $callback = $this->input->get('callback', true);
    echo $callback, '(', json_encode($_GET), ')'; // 关键代码
}

 

// 后台正确的返回结果如下:

 

二、非 jsonp 允许跨域 cookie

  后台设置 cookie 的 sameSite 属性为 None 时,必须开启 https 请求,否则跨域 cookie 会失败

  1、前端代码

$.ajax({
    url: 'https://192.168.0.123:81/api/users/logout',
    type: 'POST',
    dataType: 'json',
    crossDomain: true,
    xhrFields: {
        withCredentials: true,
    },
    data: {
        // username: 'www.ushark.net',
        // userpasswd: '92d7ddd2a010c59511dc2905b7e14f64',
    },
})
.done(function(data) {
    console.log(data);
})
.fail(function(xhr, textStatus, errorThrown) {
    console.log(xhr);
});

 

  2、后台php

$origin = $this->request->getServer('HTTP_ORIGIN') ?: '*';

header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Cookie, Authorization');

if (strtoupper($this->request->getServer('REQUEST_METHOD')) === 'OPTIONS') {
    header('HTTP/1.1 200 OK');
    exit();
}

 

posted @ 2017-11-24 11:52  gentsir  阅读(1866)  评论(0编辑  收藏  举报