问题
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:
Calling jQuery's
noConflict
function, which releases the$
identifier, orIncluding 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