通过简单的javascript(没有jQuery)通过AJAX发送表单

时间:2016-10-08 22:05:49

标签: javascript ajax

我有以下表格,我想通过AJAX请求发送。我不确定如何继续“xmlhttp.open”行。我正在尝试将视频文件上传到第三方视频托管网站(使用他们的API),他们为我提供了一个URL('upload_link_secure')来上传文件。有人可以建议吗?

我的HTML:

Most of the methods won't work for me on more than one web browser. This method is work with any amount of web browsers;

1. Put web browser into a panel and set panel enabled to false, then navigate;

    webBrowser.Parent = panelBottom;
    panelWebBrowser.Enabled = false;
    webBrowser.Navigate("http://www.google.com");

2. Define a navigated event to web browser and delay panels enabling for a second;

    private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
    {
        System.Threading.Timer timer = null;
        timer = new System.Threading.Timer((obj) =>
        {
            panelWebBrowser.Enabled = true;
            timer.Dispose();
        },null, 1000, Timeout.Infinite);
    }

我的javascript:

<form id="upload" action="'+upload_link_secure+'" method="PUT" enctype="multipart/form-data">
  <input type="file" id="vidInput">
  <button type="submit" id="submitFile" onclick="uploadMyVid(\''+upload_link_secure+'\')">Upload Video</button>
</form> 

2 个答案:

答案 0 :(得分:0)

首先,您的action属性不正确,请更改为某些端点,例如/upload

这是一个没有服务器端的简单示例。

var form = document.getElementById("upload-form"),
        actionPath = "";
        formData = null;

    var xhr = new XMLHttpRequest();

    form.addEventListener("submit", (e) => {
        e.preventDefault();
        
        formData = new FormData(form);
        actionPath = form.getAttribute("action");

        xhr.open("POST", actionPath);
        xhr.send(formData);

    }, false);
<form id="upload-form" action="/upload" method="POST" enctype="multipart/form-data">
      <input type="file" id="file">
      <button type="submit">Upload Video</button>
</form>

    

答案 1 :(得分:0)

替换<span>元素的<button>元素,使用附加到click元素的#submitFile事件处理程序; FormData() XMLHttpRequest()File <input type="file">对象中发送.files个对象;移除action元素上的<form>属性,将URL的{​​{1}}设置为XMLHttpRequest.prototype.open()请求提供的URL

PUT