XMLHttpRequest POST formData到一个新选项卡

时间:2014-07-30 15:13:31

标签: javascript firefox-addon firefox-addon-restartless

由于loadOneTab()无法使用formData

  1. 如何将formData发布到新标签页?
  2. 如何设置上述新标签前景/后台状态?
  3. 来自Using FormData Objects的一个例子:

    var formData = new FormData();
    
    formData.append("username", "Groucho");
    formData.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"
    
    // HTML file input user's choice...
    formData.append("userfile", fileInputElement.files[0]);
    
    // JavaScript file-like object...
    var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
    var blob = new Blob([content], { type: "text/xml"});
    
    formData.append("webmasterfile", blob);
    
    var request = new XMLHttpRequest();
    request.open("POST", "http://foo.com/submitform.php");
    request.send(formData);
    

    澄清:
    带有target="_blank"的普通HTML表单会将表单数据发布到新选项卡 同样,如上所述,loadOneTab()也可以将数据发布到新标签页 是否可以使用XMLHttpRequest执行此操作?

2 个答案:

答案 0 :(得分:1)

XHR与标签完全无关。如果您真的想要XHR,那么您应该使用返回的源并更新目标选项卡的文档。

否则我只会使用loadOneTab: 我会想到这样的事情会变成nsIFile:

在此处导入encodeFormData功能表:https://stackoverflow.com/a/25020668/3791822

// HTML file input user's choice...
var userfileNSIFILE = new FileUtils.File(fileInputElement.files[0].path);

// JavaScript file-like object...
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

//some code here to write blob to temp folder to make nsifile or do some stream stuff to get an nisfileoutputstream?
var blobNSIFILE = ....;

let postData = encodeFormData({
  "webmasterfile": blobNSIFILE,
  "userfile": userfileNSIFILE,
  "username": "Groucho",
  "accountnum": 123456
}, "iso8859-1");

gBrowser.loadOneTab("http://foo.com/submitform.php", {
  inBackground: false,
  postData: postData
});

答案 1 :(得分:1)

这就是我将xhr的responseText加载到选项卡中的意思,可以将粘贴复制到暂存器。

var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        switch (xhr.readyState) {
                case 4:
                   prompt('done', xhr.responseText);
                    gBrowser.loadOneTab('data:text/html, ' + encodeURIComponent(xhr.responseText), {
                      inBackground: false
                    });
            break;
          default:
        }
    };
    xhr.open("GET", "https://www.bing.com/");
    xhr.send();