TypeError: $.ajax(…) is not a function?

2020-01-23 06:18发布

I'm trying to create a simple AJAX request which returns some data from a MySQL database. Here's my function below:

function AJAXrequest(url, postedData, callback) {
    $.ajax() ({
        type: 'POST',
        url: url,
        data: postedData,
        dataType: 'json',
        success: callback
    });
}

...and here's where I call it, parsing in the required parameters:

AJAXrequest('voting.ajax.php', imageData, function(data) {
    console.log("success!");
});

Yet, my success callback does not run (as "success!" is not logged to the console), and I get an error in my console:

TypeError: $.ajax(...) is not a function.
success: callback

What does this mean? I've done AJAX requests before where the success event triggers an anonymous function inside of $.ajax, but now I'm trying to run a separate named function (in this case, a callback). How do I go about this?

标签: jquery ajax json
10条回答
地球回转人心会变
2楼-- · 2020-01-23 07:03

Checkout The Jquery Documentation

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

查看更多
▲ chillily
3楼-- · 2020-01-23 07:04

If you are using bootstrap html template remember to remove the link to jquery slim at the bottom of the template. I post this detail here as I cannot comment answers yet..

查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-01-23 07:04

For anyone trying to run this in nodejs: It won't work out of the box, since jquery needs a browser (or similar)! I was just trying to get the import to run and was logging console.log($) which wrote [Function] and then also console.log($.ajax) which returned undefined. I had no tsc errors and had autocomplete from intellij, so I was wondering what's going on.

Then at some point I realised that node might be the problem and not typescript. I tried the same code in the browser and it worked. To make it work you need to run:

require("jsdom").env("", function(err, window) {
    if (err) {
        console.error(err);
        return;
    }

    var $ = require("jquery")(window);
});

(credits: https://stackoverflow.com/a/4129032/3022127)

查看更多
我命由我不由天
5楼-- · 2020-01-23 07:05

Double-check if you're using full-version of jquery and not some slim version.

I was using the jquery cdn-script link that comes with jquery. The problem is this one by default is slim.jquery.js which doesn't have the ajax function in it. So, if you're using (copy-pasted from Bootstrap website) slim version jquery script link, use the full version instead.

That is to say use <script src="https://code.jquery.com/jquery-3.1.1.min.js"> instead of <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"

查看更多
登录 后发表回答