如何在IE 10中发送Post请求?

时间:2014-12-04 12:31:13

标签: javascript jquery ajax post form-data

如何在IE 10.0.9200中使用FormData()发送Post请求?

Html代码:

<form id="myform" enctype="multipart/form-data" method="post">
    <input id="fileInput" type="file" name="avatar" style="width:100px; height:30px"/>  
    <div class="hr hr-12 dotted"></div>
    <button type="submit" class="btn btn-sm btn-primary">Submit</button>
    <button type="reset" class="btn btn-sm">Reset</button>
</form>

Javascript代码: 发送图像上传的图像数据,并在提交后将图像发布到服务器,请帮助我处理如何处理IE 10.0.9200的formdata()和发布请求。

var fd = new FormData($form.get(0));

deferred = $.ajax({
            url: submit_url,
            type: $form.attr('method'),
            processData: false,
            contentType: false,
            dataType: 'json',
            data: fd,
            xhr: function() {
                var req = $.ajaxSettings.xhr();
                if (req && req.upload) {
                    req.upload.addEventListener('progress', function(e) {
                        if(e.lengthComputable) {    
                            var done = e.loaded || e.position, total = e.total || e.totalSize;
                            var percent = parseInt((done/total)*100) + '%';
                            //percentage of uploaded file
                        }
                    }, false);
                }
                return req;
            },
            beforeSend : function() {
            },
            success : function() {

            }
        })

1 个答案:

答案 0 :(得分:1)

使用FormData对象发送文件

您还可以使用FormData发送文件。只需在您的:

中包含文件type的元素即可
<form enctype="multipart/form-data" method="post" name="fileinfo">
  <label>Your email address:</label>
  <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
  <label>Custom file label:</label>
  <input type="text" name="filelabel" size="12" maxlength="32" /><br />
  <label>File to stash:</label>
  <input type="file" name="file" required />
  <input type="submit" value="Stash the file!" />
</form>
<div></div>

Then you can send it using code like the following:

var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {

  var oOutput = document.querySelector("div"),
      oData = new FormData(form);

  oData.append("CustomField", "This is some extra data");

  var oReq = new XMLHttpRequest();
  oReq.open("POST", "stash.php", true);
  oReq.onload = function(oEvent) {
    if (oReq.status == 200) {
      oOutput.innerHTML = "Uploaded!";
    } else {
      oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
    }
  };

  oReq.send(oData);
  ev.preventDefault();
}, false);

您还可以将File或Blob直接附加到FormData对象,如下所示:

data.append("myfile", myBlob, "filename.txt");

参考链接-https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects