layui分页跨域请求成功需同时满足:前端用$.ajaxsetup({xhrfields:{withcredentials:true}})全局配置,后端响应头必须为access-control-allow-origin具体域名且access-control-allow-credentials:true,缺一不可。

layui 分页跨域请求能成功,前提是 xhrFields: { withCredentials: true } 必须生效,且后端响应头严格匹配——漏掉任一环,请求就静默失败,控制台只报 CORS 错误,不提示具体哪边没配。
table.render 跨域必须靠 $.ajaxSetup 全局配置
layui table 底层用的是封装过的 layui.jquery.ajax,它不读取你在 table.render() 里写的 xhrFields,也不继承 headers 或 contentType 对凭据的影响。唯一可靠的方式是:在 layui.use 回调内、table.render() 之前,调用:
$.ajaxSetup({ xhrFields: { withCredentials: true } });
这个设置会作用于后续所有 layui 发起的 AJAX(包括分页、reload、tool bar 操作),否则 table.reload() 时 cookie 就断了。
- 不能只在
render里写xhrFields—— 它被忽略 - 不能只设
headers: { Cookie: 'xxx' }—— 浏览器根本不允许 JS 手动设置 Cookie 请求头 - 如果项目还用了 upload、form.submit 等模块,它们也依赖同一套全局配置,不用重复设
后端响应头必须满足三个硬性条件
前端配对了,后端少一个响应头,浏览器就会直接拦截响应,控制台报错:
Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'
后端必须同时返回:
-
Access-Control-Allow-Origin: https://your-fe-domain.com(必须是具体协议+域名,不能是*) -
Access-Control-Allow-Credentials: true(必须是字符串"true",不是布尔值) -
Access-Control-Allow-Headers包含你实际用到的头,比如Authorization、X-Requested-With
.NET Core 示例:services.AddCors(o => o.AddPolicy("AllowWithCred", p => p.AllowCredentials().WithOrigins("https://fe.example.com")))
reload 时 where 和 request 不自动更新,得显式传
table.reload() 不会重新执行 where 函数,也不会重走 request 配置逻辑——它只沿用初始化时的值。如果你的搜索条件变了,或分页参数名在不同接口中不一致,就得手动传:
table.reload('myTable', {
where: { keyword: $('#kw').val(), status: 1 },
request: { pageName: 'current_page', limitName: 'page_size' }
});
-
where推荐始终用函数形式:where: () => ({ keyword: $('#kw').val() }),避免闭包缓存旧 DOM 值 -
request如果初始化时没配,reload也不会补上默认值,仍发page/limit - 不要指望
reload自动带上新 cookie——只要全局$.ajaxSetup还在,它就一直有效
laypage 单独使用时无法跨域带 Cookie
layui.laypage.render() 是纯前端分页,它不发任何 AJAX,只生成页码 DOM。如果你用它配合手写 $.get() 或 fetch() 加载数据,那跨域逻辑完全由你自己控制——laypage 本身不参与网络请求。
换句话说:laypage 没有 xhrFields 这个概念,它不发请求;真正要跨域带 Cookie 的,是你在 jump 回调里写的那个 AJAX 调用。这时你得自己给那个请求加 credentials: 'include'(fetch)或 xhrFields: { withCredentials: true }(jQuery)。
最容易被忽略的是:很多人以为配了 $.ajaxSetup 就万事大吉,结果发现 laypage + 手写 fetch 的场景下 cookie 还是没过去——因为 fetch 不受 jQuery 全局配置影响。











