简体   繁体   中英

AJAX: jQuery ajax api vs. Javascript xhr

tl;dr: the two scripts below are not identical although I believe them to be. Why?

I'll give you some background information about this post. I'm trying to build an image uploading form that makes AJAX requests to create a dynamic upload page. Since I learned about HTML5's File API, I'm trying to use it in an AJAX request. I built my own instance by following some nice examples on MDN . My working script uses straight JS for the AJAX request, but I tried building a version that uses jQuery instead. My question is, why won't the jQuery version work properly? As far as I can tell, it's a straight port from JS xhr-style AJAX to jQuery-style AJAX. (The point of this question is to gain an academic understanding of jQuery's AJAX API; since I already have a working script, my practical needs have been fulfilled)

Here is the working Javascript AJAX request:

$("form").submit(function(){

    var file = $("input:file").get(0).files[0];
    var xhr = new XMLHttpRequest();
    var fd = new FormData();

    xhr.open("POST", "/upload", true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    };
    fd.append('img', file);
    xhr.send(fd);

    return false;

});

And the non-working jQuery version:

$("form").submit(function(){

    var fd = new FormData();
    var file = $("input:file").get(0).files[0];
    fd.append('img', file);

    $.post("/upload", fd, function(data){
        alert(data);
    });

    return false;

});        

As posted in the documentation , $.post accepts either a plain object or a string as its data argument. You cannot use FormData .

data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.

jQuery calls $.param on the second argument to $.post (and others) if it is not a string. fd is not a string, but $.param on fd is invalid. If you want to use the raw fd value, you have to set processData to false in the ajax settings: http://api.jquery.com/jQuery.ajax/

$.ajax({
    ur: "/upload",
    data: fd,
    processData: false,
}).done(function (data) {
    console.log(data);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM