You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript导入jQuery后调用$.ajax报不是函数错误如何解决?

TypeScript调用jQuery的$.ajax报错解决方案

报错TypeError: $.ajax is not a function的核心原因是:你当前是在Node.js环境运行编译后的JS代码,而jQuery本身是为浏览器DOM环境设计的库,npm安装的标准jQuery包在Node无DOM环境下不会加载ajax相关的方法,因此调用失败。


场景1:模块最终运行在Node.js环境(后端/CLI等场景)

直接弃用jQuery做网络请求,换成更适配Node环境的方案,推荐用内置fetch:

  • Node 18及以上版本已经内置fetchAPI,和浏览器端API完全一致,无需额外安装依赖,也天然支持TypeScript类型提示。
    修改后的请求代码示例(同时修正了你原有代码的逻辑错误):
class RedditJuice {
  afterbeforeStorage: Array<string>;
  totalPage: number;
  currentPage: number;

  constructor() {
    this.afterbeforeStorage = [];
    this.totalPage = 0;
    this.currentPage = 0;
  }

  fetchRedditFeed = async (afterTag: string, beforeTag: string) => {
    let url = "https://reddit.com/.json";
    // 修正原有条件判断逻辑错误
    if (afterTag && !beforeTag) {
      url = `https://reddit.com/.json?after=${afterTag}`;
    } else if (afterTag && beforeTag) {
      // 修正URL参数拼接错误,多参数用&分隔
      url = `https://reddit.com/.json?after=${afterTag}&before=${beforeTag}`;
    }
    const resp = await fetch(url);
    const getData = await resp.json();
    console.log(getData.data);
    return getData.data;
  }

  fetchPostComments = async (permalink: string) => {
    const comment_fetch_url = `https://reddit.com${permalink}.json?limit=10`;
    const resp = await fetch(comment_fetch_url);
    const data = await resp.json();
    return data[1].data;
  }
}

const rApi = new RedditJuice();
// async函数返回Promise,需要用await或者.then拿结果
rApi.fetchRedditFeed("", "").then(console.log).catch(console.error);
  • 如果你用的Node版本低于18,可以安装node-fetch包或者axios库替代,用法和内置fetch基本一致。

场景2:模块最终运行在浏览器环境

你现在直接在Node环境运行调试自然会报错,换成前端场景调试即可:

  • 用前端构建工具(Vite、Webpack等)的开发服务运行调试代码,浏览器环境下的jQuery会正常加载ajax方法
  • 不要直接用node命令运行编译后的JS文件,打包后插入到HTML页面中运行测试即可

其他优化提示

  • 你原有代码中async函数不需要手动包裹一层Promise,异步方法本身就会返回Promise,冗余的Promise包装会增加代码出错概率
  • 调用async方法时需要用await或者.then获取返回结果,直接打印只能拿到Promise对象,拿不到接口返回值
  • 注意处理请求异常,可以加try/catch包裹await语句捕获请求错误

内容的提问来源于stack exchange,提问作者CruZer0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 23:39:00