Javascript:使用AJAX而不是FETCH进行POST

时间:2018-03-02 23:01:59

标签: javascript jquery

我使用此脚本通过浏览器上传文件:

function onSubmit() {
    const url = 'uploadURl';
    fetch(url, {
            method: 'POST',
            body: input.files[0]
        }).then(function(res) {
            console.log(res);
            location.reload();
        })
        .catch(function(err) {
            console.error('Got error:', err);
        });
}

一切正常,但我想使用$.ajax代替fetch。 怎么改写?特别是,我仍然没有得到如何正确设置文件的请求体。

更新

如果我写:

$.post({
    url: 'uploadUrl',
    { data: input.files[0] }
})
.done(function() {
    console.log('File uploaded');
});

我得到:Uncaught SyntaxError: Unexpected token {

1 个答案:

答案 0 :(得分:0)

重写使用ajax会看起来像这样。

 $.post'uploadURI', {data: files.input[0]}, function(data, status) {
     //The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request
   }};

希望这会有所帮助。 Ajax是一个相对简单的把握。快速查看文档可能也会有所帮助