前端 $.ajax 跨域提交后端

Php   2026-05-24 14:04   14   0  

前端代码:

$.ajax({
    url: "https://XXXX/XXXX/XXXX",
    type: "POST",
    dataType: "json",
    data: {
        // 你的提交参数
    },
    xhrFields: {
        withCredentials: true  // 关键:允许跨域带cookie
    },
    crossDomain: true,        // 关键:声明跨域
    success: function(res){
        console.log(res);
    },
    error: function(err){
        console.log("跨域失败", err);
    }
});


后端在接口最顶部加上(PHP/Java/.NET 都通用):

// 允许你的前端域名
header("Access-Control-Allow-Origin: http://wap.dsdsd0411.com");

// 允许跨域带cookie
header("Access-Control-Allow-Credentials: true");

// 允许请求方式
header("Access-Control-Allow-Methods: POST,GET,OPTIONS");

// 放行预检请求 OPTIONS
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
    exit;
}


下一篇
没有了