"$ .ajax不是函数",但仅当调用放置在函数内部时 [英] "$.ajax is not a function", but only if call is placed inside function

查看:50
本文介绍了"$ .ajax不是函数",但仅当调用放置在函数内部时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我现在进行网络编程以来已经有一段时间了,并且设法使自己陷入一些麻烦.解决某人的问题可能微不足道,但我已经在网上进行了大量搜索.我可以找到的所有方法都是通过使用正确的jQuery源解决"$ .ajax不是函数"问题的各种方法.我已经知道了.我想知道的是,为什么不在JavaScript函数中时,ajax调用可以正常工作?一旦将其放入函数中,就会出现"$ .ajax不是函数"的问题.这是我的资料来源:

It's been a while since I've done web programming now, and managed to get myself into some trouble. Probably a trivial thing to solve for someone, but I've searched quite a bit online. All I can find are various way to solve the "$.ajax is not a function" problem by using the correct jQuery source. I've got that one figured out. What I'm wondering about is why does the ajax call work perfectly when not inside a javascript function? As soon as a put it in a function, I get the "$.ajax is not a function" problem. Here's my source:

<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>

<script type="text/javascript">
function callback() {}
$(".dropdown-item").on("click", function () {
    // Does not work
    callAjax();
});

// Does not work if called from wherever
function callAjax(){
    $.ajax({
        url: '@Url.Action("ajax", "Company")',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        type: "POST",
        data: { name: "myName" },
        success: callback
    });
}

// Does work (Same as above, just outside function)
$.ajax({
    url: '@Url.Action("ajax", "Company")',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    type: "POST",
    data: { name: "myName" },
    success: callback
});
</script>

推荐答案

这告诉我们文件中稍后的某些脚本代码是:

This tells us that some script code later in the file is either:

  1. 调用jQuery的 noConflict 函数,该函数释放 $ 标识符,或者

  1. Calling jQuery's noConflict function, which releases the $ identifier, or

包括一些脚本,这些脚本会覆盖 $ 中的值(例如:"Slim"构建中的MooTools.js,Prototype.js甚至是jQuery本身)

Including some script that overwrites the value in $ (for instance: MooTools.js, Prototype.js, or even jQuery itself in its "slim" build)

您可以通过将代码包装在使用自己的 $ 的函数中来解决此问题,如下所示:

You can solve it by wrapping your code in a function that uses its own $, like this:

(function($) {
    // ...your code here, can use `$` without worrying...
})(jQuery); // <==  Passes in `jQuery`, which is a synonym for `$`

即使后来的一些代码调用了 noConflict ,甚至完全覆盖了 $ (甚至是 jQuery ),该代码仍将继续工作,因为它在运行时获取 jQuery 的值.

Even if some later code calls noConflict, or even completely overwrites $ (or even jQuery), that code will continue to work because it grabs the value of jQuery as of when it runs.

这篇关于"$ .ajax不是函数",但仅当调用放置在函数内部时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆