[英]Using jQuery (ajax) with TypeScript
I have installed the jQuery typings in my TypeScript project. 我在我的TypeScript项目中安装了jQuery类型。 I can type $.ajax(...) without any compile errors in VS Code.
我可以在VS Code中输入$ .ajax(...)而不会出现任何编译错误。 However, when I check it in localhost, I get an error saying that "$ is not defined".
但是,当我在localhost中检查它时,我收到一条错误,指出“$未定义”。 I tried to fix it by importing jQuery like so:
我尝试通过导入jQuery来修复它,如下所示:
import * as jQuery from "jquery"
I imported express in the same way, and it works. 我以同样的方式导入快递,它的工作原理。
When I type "jquery." 当我输入“jquery”时。 in VS Code, VS Code auto-suggests "ajax" as a method call, so it knows about my import.
在VS Code中,VS Code自动建议将“ajax”作为方法调用,因此它知道我的导入。 But when I check it in localhost again, it tells me jquery.ajax is not a function.
但是当我再次在localhost中检查它时,它告诉我jquery.ajax不是一个函数。
My test ajax call: 我的测试ajax调用:
jquery.ajax("test.html", {
success: function () {
alert("success");
},
error: function () {
alert("error");
}
});
How can you make an ajax call with jQuery with TypeScript? 如何使用TypeScript与jQuery进行ajax调用?
What typings do is tell your TypeScript what methods are safe to interact with a certain JavaScript ( not TypeScript) file. 输入的内容是告诉您的TypeScript哪些方法可以安全地与某个JavaScript( 而不是 TypeScript)文件进行交互。 They're like header files in C++.
它们就像C ++中的头文件。 You still need to actually have the relevant code imported to your page in some way.
您仍然需要以某种方式将相关代码导入到您的页面中。 A basic way to do so would be to add something like this in your HTML's
<head>
: 一个基本的方法是在你的HTML的
<head>
添加这样的东西:
<script src="scripts/jquery.js"></script>
If you're not using a module system like CommonJS or AMD (something you would have to set up yourself), you may want to remove the import
statement as it's liable to confuse you. 如果您没有使用像CommonJS或AMD这样的模块系统(您必须自己设置),您可能需要删除
import
语句,因为它可能会让您感到困惑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.