“$.ajax is not a function”, but only if call is placed inside function

随声附和 提交于 2021-01-29 11:43:16

问题


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>

回答1:


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

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

  2. 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 `$`

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.



来源:https://stackoverflow.com/questions/56856812/ajax-is-not-a-function-but-only-if-call-is-placed-inside-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!