简体   繁体   English

需要帮助来编写等效于XHR请求的Jquery $ .ajax请求

[英]Need help to write a Jquery $.ajax request equivalent to an XHR request

Working XHR request that sends a file with all required request headers set. 工作XHR请求,该请求发送带有所有必需请求标头的文件。

var upload = function (file) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Admin/Upload', true);
    xhr.setRequestHeader('X-Filename', file.name);
    xhr.setRequestHeader('pageid', pageid);
    xhr.setRequestHeader('catid', catid);
    xhr.send(file);
}

Trying to get the below working (Using jQuery 1.7.2) 尝试使以下工作正常(使用jQuery 1.7.2)

var xhr = new XMLHttpRequest();

var upload = function (file, xhr) {
    $.ajax
    ({
        url: '/Admin/Upload',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('X-Filename', file.name);
            xhr.setRequestHeader('pageid', pageid);
            xhr.setRequestHeader('catid', catid);

        },
        data: file,
        success: function (data) {

            alert('Load was performed.');
        }

    });
}

Update: Ok, so I have progressed a bit and the request now actually hits the action method, however there is no data in the input stream and all the file key arrays are null, so the actual file data does no appear to be going through. 更新:好的,所以我取得了一些进展,现在请求实际上到达了操作方法,但是输入流中没有数据,并且所有文件键数组都为空,因此实际文件数据似乎没有通过。 The request headers are coming through fine. 请求标头很好。 The (data: file) is different I presume to xhr.send(file) ? 我认为(data:file)与xhr.send(file)不同吗?

Now using this: 现在使用这个:

var upload = function (file) 
{
    $.ajax
    ({
        url: "/Admin/Upload",
        headers: { catid: catid, pageid: pageid },
        processData: false,
        data: file,
        success: function (data) {

            alert('Load was performed.');
        }

    });
}

Try also set contentType to false and type to 'POST' . 还要尝试将contentType设置为false然后type 'POST'

$.ajax({
    url: "/Admin/Upload",
    type: 'POST',
    headers: { catid: catid, pageid: pageid },
    processData: false,
    contentType: false,
    data: file,
    success: function (data) {
        alert('Load was performed.');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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