如何获取jQuery ajax POST请求返回值并实现公共请求函数复用
问题原因与解决方案
为什么你拿不到预期返回值
你遇到的问题核心有两点:
$.ajax()本身返回的是jqXHR异步请求对象,不是回调函数里的返回值,所以你外层返回的test是请求对象而非接口返回的id,自然弹出[object Object]- 写在
complete回调里的return id只会把值返回给ajax内部的回调处理逻辑,不会透传到buscaIdEmpresa函数外层。另外你写的async: false同步请求是严重不推荐的写法,会阻塞页面所有交互直到请求完成,现代浏览器已经在逐步废弃同步XHR能力。
规范实现方案
jQuery的jqXHR对象本身符合Promise A+规范,我们直接用异步Promise的写法处理即可,有两种常用写法:
第一步:先修改公共请求函数
function buscaIdEmpresa() { const jsonEmail = { "email": emailCurrentUser }; const jsonEmailString = JSON.stringify(jsonEmail); // 直接返回jqXHR对象,支持Promise调用 return $.ajax({ url: "https://localhost:44326/test", type: "post", crossDomain: true, data: jsonEmailString, contentType: "application/json", dataType: "json" }); }
调用方式1:用then链式调用
function carregaConfigList() { buscaIdEmpresa() .then(function(id) { // 这里拿到的就是接口返回的id,后续逻辑都在这个块里执行 alert(id); }) .catch(function(err) { // 统一处理请求错误 console.error('获取企业ID失败', err); }) }
调用方式2:用async/await(写法更贴近同步逻辑,更易读)
async function carregaConfigList() { try { const id = await buscaIdEmpresa(); alert(id); // 后续逻辑直接写即可 } catch (err) { console.error('获取企业ID失败', err); } }
更高复用性的封装
如果要避免每次写重复的ajax配置,可以抽通用请求函数,所有页面都能复用:
// 通用POST请求封装,所有接口请求都可以调用 function commonPost(url, reqData) { return $.ajax({ url: url, type: "post", crossDomain: true, data: JSON.stringify(reqData), contentType: "application/json", dataType: "json" }); } // 简化后的查询企业ID函数 function buscaIdEmpresa() { return commonPost("https://localhost:44326/test", { email: emailCurrentUser }); }
内容的提问来源于stack exchange,提问作者Jalkun
相关产品推荐
相关产品推荐

